Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.For example, given
preorder = [3,9,20,15,7]inorder = [9,3,15,20,7]
Return the following binary tree:
3 / \ 9 20 / \ 15 7
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */10 class Solution {11 public TreeNode buildTree(int[] preorder, int[] inorder) {12 if (preorder == null || inorder == null || preorder.length == 0 || inorder.length != preorder.length) return null;13 return buildTree(inorder, 0, preorder, 0, inorder.length);14 }15 16 public TreeNode buildTree(int[] inorder, int inStart, int[] preorder, int preStart, int length) {17 if (length == 0) return null;18 TreeNode root = new TreeNode(preorder[preStart]);19 int index = findIndex(inorder, root.val);20 root.left = buildTree(inorder, inStart, preorder, preStart + 1, index - inStart);21 root.right = buildTree(inorder, index + 1, preorder, preStart + (index - inStart) + 1, length - (index - inStart) - 1);22 return root; 23 }24 25 public int findIndex(int[] inorder, int val) {26 for (int i = 0; i < inorder.length; i++) {27 if (inorder[i] == val) {28 return i;29 }30 }31 return -1;32 }33 }