Output: Tree root
Example: If the given traversal is {10, 5, 1, 7, 40, 50}, then the output should be root of following tree.
10
/ \
5 40
/ \ \
1 7 50
Solution:
static class TreeNode {
public TreeNode(int v) { val = v;}
int val;
TreeNode left;
TreeNode right;
}
public static void main(String[] args) {
// 10
// 5 40
// 1 7 50
int pre[] = new int[] { 10, 5, 1, 7, 40, 50 };
int size = pre.length;
TreeNode root = constructTree(pre, 0, size - 1);
printInorder(root);
}
public static TreeNode constructTree(int[] pre, int l, int h) {
if (l > h) return null;
if (l == h) return new TreeNode(pre[l]);
TreeNode root = new TreeNode(pre[l]);
int ind = l + 1;
// Find the first index which is greater than or equal to root
for (int i = l + 1; i <= h; i++) {
if (root.val < pre[i]) {
ind = i;
break;
}
}
root.left = constructTree(pre, l + 1, ind - 1);
root.right = constructTree(pre, ind, h);
return root;
}
public static TreeNode constructTreeIterative(int[] pre, int l, int h) {
if (l > h) return null;
Stack<TreeNode> stack = new Stack<>();
TreeNode root = new TreeNode(pre[l]);
stack.push(root);
for (int i = l + 1 ; i <= h ; i++) {
int val = pre[i];
// Handle left side
if (stack.peek().val > val) {
TreeNode left = new TreeNode(val);
stack.peek().left = left;
stack.push(left);
} else {
// Handle right side and find its paraent
TreeNode rightParent = null;
while(!stack.isEmpty() && stack.peek().val < val) {
rightParent = stack.pop();
}
rightParent.right = new TreeNode(val);
stack.push(rightParent);
}
}
return root;
}
public static void printInorder(TreeNode node) {
if (node == null) {
return;
}
printInorder(node.left);
System.out.print(node.val + " ");
printInorder(node.right);
}
No comments:
Post a Comment