Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
本题采用递归的方式来进行:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
if(preorder == null || inorder == null){
return null;
}
HashMap<Integer,Integer> map = new HashMap<>();
for(int i = 0; i < inorder.length;i++){
map.put(inorder[i],i);
}
return recursion(preorder,inorder,0, preorder.length-1,0,inorder.length-1,map);
}
public TreeNode recursion(int[] preorder, int[] inorder, int preLeft, int preRight, int inLeft, int inRight, HashMap<Integer, Integer> map){
if(preLeft > preRight || inLeft > inRight){
return null;
}
TreeNode root = new TreeNode(preorder[preLeft]);
int index = map.get(root.val);
root.left = recursion(preorder,inorder,preLeft+1, index-inLeft+preLeft,inLeft,index-1,map);
root.right = recursion(preorder,inorder,index-inLeft+preLeft+1,preRight,index+1,inRight,map);
return root;
}
}