剑指 Offer 07. 重建二叉树

输入某二叉树的前序遍历和中序遍历的结果,请重建该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。

 

例如,给出

前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]
返回如下的二叉树:

   3
  / \
 9  20
/ \
15 7

class Solution {
    HashMap<Integer,Integer> map;
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        map = new HashMap<>();
        for(int i=0;i<inorder.length;i++)
        {
            map.put(inorder[i], i);
        }
        return process(preorder, inorder, 0, preorder.length-1, 0, inorder.length-1);
        
    }
    public TreeNode process(int[] preorder,int[] inorder,int pre_left,int pre_right,int in_left,int in_right)
    {
        if(pre_left>pre_right)
            return null;
        int root_pre = pre_left;
        int root_in = map.get(preorder[root_pre]);
        TreeNode root = new TreeNode(preorder[root_pre]);
        int size_left_tree = root_in - in_left;
        root.left = process(preorder, inorder, pre_left+1, pre_left+size_left_tree, in_left, root_in-1);
        root.right = process(preorder, inorder, pre_left+size_left_tree+1, pre_right,root_in+1, in_right);
        return root;
    }
}

 

posted @ 2021-04-18 18:15  γGama  阅读(28)  评论(0编辑  收藏  举报