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

题目描述:

根据一棵树的前序遍历与中序遍历构造二叉树。

注意:
你可以假设树中没有重复的元素。

例如,给出

前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]

返回如下的二叉树:

   3
   / \
  9  20
    /  \
   15   7

思路分析:

废话不多说,直接来想思路,首先思考,根节点应该做什么。

类似上一题,我们肯定要想办法确定根节点的值,把根节点做出来,然后递归构造左右子树即可。(都是套路)

具体思路可参照公众号文章https://mp.weixin.qq.com/s/OlpaDhPDTJlQ5MJ8tsARlA

class Solution {
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        return build(preorder,0,preorder.length-1,
                    inorder,0,inorder.length-1);
    }
    
    TreeNode build(int[] preorder,int prestart,int preend,
                   int[] inorder,int instart,int inend){
        if(prestart>preend){
            return null;
        }
        int rootVal=preorder[prestart];
        int index=0;
        for(int i=instart;i<=inend;i++){
            if(inorder[i]==rootVal){
                index=i;
                break;
            }
        }
        int leftsize=index-instart;
        TreeNode root=new TreeNode(rootVal);
        root.left=build(preorder,prestart+1,prestart+leftsize,
                        inorder,instart,index-1);
        root.right=build(preorder,prestart+leftsize+1,preend,
                        inorder,index+1,inend);

        return root;

    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小小谢先生

支持知识付费

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值