105. Construct Binary Tree from Preorder and Inorder Traversal
身体不好
1 class Solution { 2 public TreeNode buildTree(int[] preorder, int[] inorder) { 3 return helper(0, 0, inorder.length - 1, preorder, inorder); 4 5 } 6 7 public TreeNode helper(int preStart, int inStart, int inEnd, int[] preorder, int[] inorder) { 8 if(preStart > preorder.length - 1 || inStart > inEnd) { 9 return null; 10 } 11 TreeNode root = new TreeNode(preorder[preStart]); 12 int rootIndex = 0; 13 for(int i = inStart; i <= inEnd; i++) { // i 不是 =0 是等于 = inStart 14 if(root.val == inorder[i]) { 15 rootIndex = i; 16 } 17 } 18 root.left = helper(preStart + 1, inStart, rootIndex - 1, preorder, inorder); 19 root.right = helper(preStart + rootIndex - inStart + 1, rootIndex + 1, inEnd, preorder, inorder); 20 return root; 21 } 22 }