【剑指 Offer 07. 重建二叉树】

解题思路

利用前序和中序遍历来重建二叉树
其中中序遍历是必不可少的
思路:
1:在先序遍历中找到根节点,(在本解法中,将中序遍历数组值和对应索引存在hashmap中,便于以后根据先序遍历的根来找在中序
遍历的索引)
2:开始递归,如果in_left>in_right,就return null
3:其中root.left=recur(pre_root+1,in_left,i-1)
详细的看代码注释吧
流程推导


image.png

代码

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    Map map=new HashMap();
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        for(int i=0;iright) return null;
         TreeNode root=new TreeNode(preorder[index]);
        int i=map.get(preorder[index]);//记录子树的根在中序数组的索引
        root.left=dfs(preorder,index+1,left,i-1);
        root.right=dfs(preorder,i - left + index + 1,i+1,right);
        return root;
    }
}

你可能感兴趣的:(【剑指 Offer 07. 重建二叉树】)