Note:
You may assume that duplicates do not exist in the tree.
---
Solution: The first node in the preorder is always the root node. Find this same node in the inorder. All the nodes to the left belong to the left sub-tree. All the nodes to the right belong to the right sub-tree. In each recursion, always pick the next node from the preorder as the root node.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
private final Map<Integer, Integer> inOrderIndexMap = new HashMap<>();
private int preOrderIndex = 0;
public TreeNode buildTree(int[] preorder, int[] inorder) {
if (preorder.length == 0) return null;
for (int i = 0; i < inorder.length; i++) {
inOrderIndexMap.put(inorder[i], i);
}
return buildTree(preorder, inorder, 0, inorder.length - 1);
}
private TreeNode buildTree(int[] preorder, int[] inorder, int i0, int i1) {
if (i0 > i1) return null;
TreeNode root = new TreeNode(preorder[preOrderIndex++]);
int rootIndex = inOrderIndexMap.get(root.val);
root.left = buildTree(preorder, inorder, i0, rootIndex - 1);
root.right = buildTree(preorder, inorder, rootIndex + 1, i1);
return root;
}
}
No comments:
Post a Comment