Given Preorder and inorder traversal of a tree, construct the binary tree.
Note:
Assume that duplicates does not exist in the tree.
Problem solving idea One:
Preorder[0] As root, dividing the Inorderleft, Preorderleft, Inorderright, preorderright four arrays respectively, and then Root.left=buildtree ( Preorderleft,inorderleft); Root.right=buildtree (Preorderright,inorderright)
The Java implementation is as follows:
Public TreeNode Buildtree (int[] preorder, int[] inorder) {if (Preorder.length = = 0 | | preorder.length = inorder.length) re Turn null; TreeNode root = new TreeNode (preorder[0]), int index = 0;for (int i = 0; i < inorder.length; i++) if (inorder[i] = = root. val) {index = 0;break;} int[] Inorderleft = new Int[index], preorderleft = new int[index];int[] Inorderright = new Int[inorder.length-1-index] , preorderright = new int[inorder.length-1-index]; Set<integer> inorderleftset=new hashset<integer> (); for (int i = 0; i < inorderleft.length; i++) { Inorderleft[i] = Inorder[i];inorderleftset.add (Inorder[i]);} for (int i = 0; i < inorderright.length; i++) Inorderright[i] = Inorder[index + i + 1];int j = 0, k = 0;for (int i = 0; i < preorder.length; i++) {if (Inorderleftset.contains (Preorder[i])) Preorderleft[j++]=preorder[i];else if (preorder[i]!=root.val) Preorderright[k++]=preorder[i];} if (Buildtree (preorderleft,inorderleft)!=null) Root.left=buildtree (preorderleft,inorderleft); if (Buildtree (preorderright,inorderright)!=null) Root.right=buildtree (preorderright,inorderright); return root;}
Result: TimeLimit exceeded
Two ways to solve problems:
Java for Leetcode Construct Binary Tree from preorder and inorder traversal