Construct Binary Tree from preorder and inorder traversal
Given Preorder and inorder traversal of a tree, construct the binary tree.
Note:
Assume that duplicates does not exist in the tree.
Solution 1:
1. Find The root node from the preorder. (It is the first node.)
2. Try to find the position of the root in the inorder. Then we can get the number of nodes in the left tree.
3. Recursive call, constructs Saozi right subtree.
Example:
Pre:4 2 1 3 6 5 7
Inorder:1 2 3 4 5 6 7
1 /**2 * Definition for binary tree3 * public class TreeNode {4 * int val;5 * TreeNode left;6 * TreeNode right;7 * TreeNode (int x) {val = x;}8 * }9 */Ten Public classSolution { One PublicTreeNode Buildtree (int[] Preorder,int[] inorder) { A //Bug 3:consider when length is 0. - if(Preorder = =NULL|| Inorder = =NULL|| Preorder.length = = 0 | | Preorder.length! =inorder.length) { - return NULL; the } - - //Bug 4:end index is length-1. - returnBuildtree (preorder, inorder, 0, preorder.length-1, 0, Preorder.length-1); + } - + PublicTreeNode Buildtree (int[] Preorder,int[] inorder,intPrestart,intPreend,intInstart,intinend) { A //base case; at if(Prestart >preend) { - return NULL; - } - - intRootval =Preorder[prestart]; -TreeNode root =NewTreeNode (rootval); in - intpos =Findtarget (inorder, Rootval, Instart, inend); to + //Bug 5:left number is Pos-instart can ' t add 1 - intLeftnum = pos-Instart; the *Root.left = Buildtree (preorder, inorder, Prestart + 1, Prestart + leftnum, Instart, pos-1); $Root.right = Buildtree (preorder, inorder, Prestart + leftnum + 1, preend, POS + 1, inend);Panax Notoginseng - returnRoot; the } + A //bug 1:return type required. the //Bug 2:this is not a BST. Can ' t use binary search. + Public intFindtarget (int[] A,intTargetintStartintend) { - for(inti = start; I <= end; i++) { $ if(target = =A[i]) { $ returni; - } - } the - return-1;Wuyi } the}
View Code
GITHUB:
Https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/tree/BuildTree.java
Leetcode:construct Binary Tree from preorder and inorder traversal problem solving report