Given Preorder and inorder traversal of a tree, construct the binary tree.
Note:
Assume that duplicates does not exist in the tree.
Give the pre-order traversal and the middle sequence traversal, and then seek the tree.
It's very regular. Recursion can be achieved.
/*** Definition for a binary tree node. * public class TreeNode {* int val; * TreeNode left; * TreeNode rig Ht * TreeNode (int x) {val = x;} }*/ Public classSolution { PublicTreeNode Buildtree (int[] Preorder,int[] inorder) { intLen =preorder.length; if(len = = 0) return NULL; returnHelper (preorder,0,len-1,inorder,0,len-1); } PublicTreeNode Helper (int[] Preorder,intPre_start,intPre_end,int[] inorder,intIn_start,intin_end) { if(Pre_start > Pre_end | | in_start >in_end)return NULL; TreeNode node=NewTreeNode (Preorder[pre_start]); intSize = 0; for(inti = In_start;i<=in_end && inorder[i]! = preorder[pre_start];i++,size++) ; Node.left= Helper (preorder,pre_start+1,pre_start+size,inorder,in_start,in_start+size-1); Node.right= Helper (preorder,pre_start+size+1,pre_end,inorder,in_start+size+1, In_end); returnnode; }}
Speed is not fast, the fastest answer is also a reference.
It's not how good the algorithm is, but he's
for (int i = In_start;i<=in_end && inorder[i]! = preorder[pre_start];i++,size++) ;
Here the traversal is chosen from the backward forward, due to the particularity of the test data, resulting in the rapid response.
Leetcode Construct Binary Tree from preorder and inorder traversal-----java