(二叉树)从中序与后序遍历序列构造二叉树

 后序遍历的最后一个值是树的根节点,在中序遍历中找到该节点,根据中序遍历的特点(左子树-根-右子树),所以在中序遍历中,把根节点左边的值都放进左子树递归,把根节点右边的值都放进右子树递归。

class Solution {
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        int len1=inorder.length-1;
        int len2=postorder.length-1;
        TreeNode root=reBuildTree(inorder,0,len1,postorder,0,len2);
        return root;
    }
    public TreeNode reBuildTree(int[] inorder,int start1,int end1,int[] postorder,int start2,int end2){
        if(start1>end1||start2>end2)
            return null;
        TreeNode root=new TreeNode(postorder[end2]);
        for(int i=start1;i<=end1;i++){
            if(inorder[i]==postorder[end2]){
                root.left=reBuildTree(inorder,start1,i-1,postorder,start2,start2+i-start1-1);
                root.right=reBuildTree(inorder,i+1,end1,postorder,start2+i-start1,end2-1);
                break;
            }
       }
        return root;
    }
    
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值