Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
Https://oj.leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/
Idea: similar to the above question, start with preorder to find the root node and then distinguish the left and right subtree in the middle order.
Because Java does not support returning the addresses of elements behind the array, it is not as elegant as C/C ++. You need to pass a range or copy the array locally.
public class Solution { public TreeNode buildTree(int[] preorder, int[] inorder) { if (inorder.length == 0 || preorder.length == 0) return null; TreeNode res = build(preorder, 0, preorder.length, inorder, 0, inorder.length); return res; } private TreeNode build(int[] pre, int a, int b, int[] in, int c, int d) { if (b - a <= 0) return null; TreeNode root = new TreeNode(pre[a]); int idx = -1; for (int i = c; i < d; i++) { if (in[i] == pre[a]) idx = i; } // use the len, not idx int len = idx - c; root.left = build(pre, a + 1, a + 1 + len, in, c, c + len); root.right = build(pre, a + 1 + len, b, in, c + 1 + len, d); return root; } public static void main(String[] args) { new Solution().buildTree(new int[] { 3, 9, 20, 15, 7 }, new int[] { 9, 3, 15, 20, 7 }); }}View code