Repository navigation
Expand file tree
/
Copy pathconvertTwoDimensionalArrayIntoBinaryTree.java
More file actions
120 lines (89 loc) · 2.44 KB
/
Copy pathconvertTwoDimensionalArrayIntoBinaryTree.java
File metadata and controls
120 lines (89 loc) · 2.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author pg027919
*
*/
public class convertTwoDimensionalArrayIntoBinaryTree {
public static void main(String args[]){
/*2 elements of nested array act as child parent node so
this program converts inputArr into following binary tree
1
2 3
4 5 6
*/
int[][] inputArr = {
{2, 4},
{1, 2},
{3, 6},
{1, 3},
{2, 5}
};
Map<Integer,List<Integer>> lookupMap= createMap(inputArr);
System.out.println("hash map: "+lookupMap);
int root = getRoot(lookupMap);
System.out.println("Root: "+root);
Node rt= new Node();
rt.val = root;
createTree(rt, lookupMap);
traverse(rt);
}
private static void traverse(Node current) {
if( current != null){
System.out.println(current.val+" ");
traverse(current.leftChild);
traverse(current.rightChild);
}
}
private static int getRoot(Map<Integer, List<Integer>> treeMap) {
int root = -1;
List<Integer> valList = new ArrayList<Integer>();
for (int key : treeMap.keySet()){
valList.addAll(treeMap.get(key));
}
for (int key : treeMap.keySet()){
if(!valList.contains(key))
root = key;
}
return root;
}
// create map to store child-parent relationship
private static Map<Integer, List<Integer>> createMap(int[][] arr) {
Map<Integer, List<Integer>> treeMap = new HashMap<Integer,List<Integer>>();
List<Integer> tempList;
for( int i = 0; i < arr.length; i++) {
if (treeMap.containsKey(arr[i][0])){
tempList = treeMap.get(arr[i][0]);
}
else
tempList = new ArrayList<Integer>();
tempList.add(arr[i][1]);
treeMap.put(arr[i][0], tempList);
}
return treeMap;
}
// After getting root create tree using hash map
private static void createTree(Node node, Map<Integer, List<Integer>> treeMap) {
List<Integer> childList = treeMap.get(node.val);
if(childList == null)
return;
System.out.println("childList: "+childList);
Node nodeLeft = new Node();
nodeLeft.val = childList.get(0);
node.leftChild = nodeLeft;
Node nodeRight = new Node();
if(childList.size() == 2){
nodeRight.val = childList.get(1);
node.rightChild = nodeRight;
}
createTree(nodeLeft, treeMap);
createTree(nodeRight, treeMap);
}
}
class Node {
int val;
Node leftChild;
Node rightChild;
}