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

思路:
1、从前序结果中取树根节点的内容
2、从中序遍历中找到根的位置pos,然后将中序数据分割成两部分
[ left , pos )和[ pos+1 , right ]
3、创建根节点。
递归创建根节点的左子树
递归创建根节点的右子树

class Solution {
    int index=0;//index是为了从前序遍历中找根节点的位置
    //preorder:前序遍历结果    inorder:中序遍历结果     [left,right]:标记树中节点在inorder中的范围
    private TreeNode BuilidTree(int[] preorder,int[] inorder,int left,int right){
        if(index >= preorder.length || left >= right){
            return null;
        }
        //在中序遍历结果中找根的位置
        //确认根节点的左右子树的区间
        int rootIdx=left;
        while(rootIdx<right){
            if(preorder[index]==inorder[rootIdx]){
                break;
            }
            rootIdx++;
        }
        //创建根节点
        TreeNode root=new TreeNode(preorder[index]);
        //递归创建根节点的左子树:[left,inrootIdx)
        ++index;
        root.left=BuilidTree(preorder,inorder,left,rootIdx);
        //递归创建根节点的右子树:[rootIdx+1,right]
        root.right=BuilidTree(preorder,inorder,rootIdx+1,right);
        return root;
    }
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        return BuilidTree(preorder,inorder,0,inorder.length);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值