105. Construct Binary Tree from Preorder and Inorder Traversal - Medium
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
time: O(nlogn) ~ O(n^2), space: O(height)
/** * 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 == 0 || preorder.length != inorder.length) { return null; } return buildTree(preorder, inorder, 0, 0, inorder.length - 1); } public TreeNode buildTree(int[] preorder, int[] inorder, int pre_start, int in_start, int in_end) { if(pre_start > preorder.length - 1 || in_start > in_end) { return null; } TreeNode root = new TreeNode(preorder[pre_start]); int idx = 0; for(int i = in_start; i <= in_end; i++) { if(inorder[i] == preorder[pre_start]) { idx = i; } } root.left = buildTree(preorder, inorder, pre_start + 1, in_start, idx - 1); root.right = buildTree(preorder, inorder, pre_start + (idx - in_start + 1), idx + 1, in_end); return root; } }