Traversing the binary tree is configured in accordance with the sequence preorder traversal of a tree.
Note:
You can assume that the tree does not duplicate elements.
For example, given
a preorder traversal preorder = [ 3 , . 9 , 20 is , 15 , . 7 ]
preorder InOrder = [ . 9 , 3 , 15 , 20 is , . 7 ]
returns the following binary tree:
3
/ \
. 9 20 is
/ \
15 . 7
Idea: using the idea of divide and conquer to solve the problem
Specific problem-solving steps:
1. The preorder traversal, we can know that the first element is the root of the given array pre [0], then we can find a value equal to the pre preorder [0] position, the first half of the location part is the left subtree, the right half is the right subtree,
2. Repeat 1 until traversed
Codes are as follows:
public class Solution {
public int preIndex = 0;
//查找pre[pri]的位置
public int find(int[] inorder, int inbegin,int inend,int val){
for(int i = inbegin;i<=inend;i++){
if(inorder[i] == val) return i;
}
return -1;
}
public TreeNode buildTreeChild(int[] preorder, int[] inorder, intinbegin, int inend) {
if (inbegin> inend) return null ;
TreeNode root = new TreeNode (preorder [preIndex]);
int index = find (ordered, inbegin, inend, preorder [preIndex]);
if (index == - 1 ) return null ;
preIndex ++ ;
root.left = buildTreeChild (preorder, inorder, inbegin, index- 1 );
root.right = buildTreeChild (preorder, inorder, index + 1 , inend);
return root;
}
public TreeNode buildTree(int[] preorder, int[] inorder) {
if(preorder == null || inorder == null) return null;
return buildTreeChild(preorder,inorder,0,inorder.length-1);
}
}