Assume you have a perfect binary tree, something like this
0
/ \
1 2
/ \ / \
3 4 5 6
/ \ / \ / \ / \
7 8 9 10 11 12 13 14
Given its depth and output of node values as a depth first search array, eg.
Depth: [4]
Dfs Array: [0,1,3,7,8,4,9,10,2,5,11,12,6,13,14]
write code that returns it as a Binary Tree. How would you do it(recursive/non-recursive)?
I am not sure if it is possible to solve this recursively since I don't have info about which nodes are leaves Vs non leaves. Having that information allows one to construct the tree recursively. Without recursion, I was trying to do something like this, but I am getting stuck on getting this all the way.
TreeNode {
int value;
TreeNode left;
TreeNode right;
TreeNode(int value) {
this.value = value;
}
}
TreeNode makeTree(int[] dfs, int depth) {
TreeNode root = new TreeNode(dfs[0]);
Deque<TreeNode> dq = new LinkedList<>();
dq.addFirst(root);
while (!dq.isEmpty()) {
int i;
for (i = 1; i < depth - 1; i++) {
TreeNode t = dq.getFirst();
t.left = new TreeNode(dfs[i]);
dq.addFirst(t.left);
}
TreeNode t = dq.getFirst();
t.left = new TreeNode(dfs[i++]);
dq.addFirst(t.left);
t.right = new TreeNode(dfs[i++)];
dq.addFirst(t.right);
}
// More code here to construct the tree?
.........
// return the root
return dq.getLast();
}
