剑指offer_07_重建二叉树
输入某二叉树的前序遍历和中序遍历的结果,请重建该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private HashMap<Integer,Integer> hashmap;
public TreeNode MybuildTree(int[] preorder,int[] inorder,int preleft,int preright,int inleft,int inright){
if(preleft>preright){
return null;
}
//获取前序遍历中的根节点
int pre_root = preleft;
//获取中序遍历中的根节点
int in_root = hashmap.get(preorder[pre_root]);
//获取左子树的长度
int left_size = in_root - inleft;
//建立当前根节点
TreeNode node = new TreeNode(preorder[pre_root]);
node.left = MybuildTree(preorder,inorder,pre_root+1,pre_root+left_size,inleft,in_root-1);
node.right = MybuildTree(preorder,inorder,pre_root+left_size+1,preright,in_root+1,inright);
return node;
}
public TreeNode buildTree(int[] preorder, int[] inorder) {
hashmap = new HashMap<Integer,Integer>();
if(preorder.length==0||inorder.length==0){
return null;
}
for(int i = 0;i<inorder.length;i++){
hashmap.put(inorder[i],i);
}
return MybuildTree(preorder,inorder,0,preorder.length-1,0,inorder.length-1);
}
}
由此可以找出递归的关系.