LeetCode 105. 从前序与中序遍历序列构造二叉树

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    // 我们需要跟踪根的位置:前序和中序 都需要
    // 但是前序中根的位置是有迹可循的:i=0,i+左子树节点数...
    private TreeNode helper(int lo,int hi,int preRootIndex,int[] preorder,int[] inorder){
        if(lo>hi||preRootIndex>=preorder.length){
            return null;
        }
        if(lo==hi){
            return new TreeNode(inorder[lo]);
        }
        TreeNode root=new TreeNode(preorder[preRootIndex]);
        // 得到作为根的元素在中序中的位置
        int inRootIndex=val2index.get(root.val);
        // 左子树的根就在前序中根的后面一个(如果根为空?
        // 如果根为空,那么lo和inRootIndex就相等,那么inRootIndex-1就小于lo,返回null
        int preLeftRootIndex=preRootIndex+1;
        root.left=helper(lo,inRootIndex-1,preLeftRootIndex,preorder,inorder);
        // 右子树的根,在当前根+左子树节点数+1
        int preRightRootIndex=preRootIndex+(inRootIndex-1-lo+1)+1;
        root.right=helper(inRootIndex+1,hi,preRightRootIndex,preorder,inorder);
        return root;
    }
    private HashMap<Integer,Integer> val2index=new HashMap<>();
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        for(int i=0;i<inorder.length;i++){
            val2index.put(inorder[i],i);
        }
        return helper(0,inorder.length-1,0,preorder,inorder);
    }
}

这个题以前做过 但是竟然再做还遇到了一些麻烦 看来还是要多模拟一下做法?(就考试做的那种,把算法搞清楚

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值