Construct Binary Tree from Preorder and Inorder Traversal
preorder = [3,9,20,15,7]
inorder = [9,3,15,20,7] 3
/ \
9 20
/ \
15 7Analysis
Solution
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
if (preorder == null || inorder == null || preorder.length != inorder.length) {
return null;
}
return buildTreeHelper(preorder, inorder, 0, preorder.length - 1, 0, inorder.length - 1) ;
}
TreeNode buildTreeHelper(int[] preorder, int[] inorder, int preStart, int preEnd, int inStart, int inEnd) {
if (inStart > inEnd) {
return null;
}
int rootPosition = findPosition(inStart, inEnd, inorder, preorder[preStart]);
TreeNode root = new TreeNode(preorder[preStart]);
root.left = buildTreeHelper(preorder, inorder, preStart + 1, preStart + rootPosition - inStart, inStart, rootPosition - 1 );
root.right = buildTreeHelper(preorder, inorder, preEnd - inEnd + rootPosition + 1, preEnd, rootPosition + 1, inEnd );
return root;
}
int findPosition (int start, int end, int[] arr, int target) {
int i;
for (i = start; i <= end; i++) {
if (arr[i] == target) {
return i;
}
}
return -1;
}
}Using Pre-built Hashmap for Index Lookup
*LeetCode Official Solution
Reference
Last updated