从中序遍历和后序遍历构造二叉树

前序遍历顺序 根节点 左子树 右子树 中序遍历 左子树 根节点 右子树 后序遍历 左子树
右子树 根节点

这道题和从前序与中序遍历序列构造二叉树,只是 root.right=helper(mid+1,right);
root.left=helper(left,mid);
顺序发生改变 仍然是使用全局变量post_index,
从后往前 创建结点

class Solution {
    int post_index;
    int[] inorder;
    int[] postorder;
    Map<Integer,Integer> map=new HashMap<>();
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        this.inorder=inorder;
        this.postorder=postorder;
        this.post_index=postorder.length-1;
        int in_index=0;
        for(int num:inorder){
            map.put(num,in_index++);
        }
        return helper(0,inorder.length);
    }
    public TreeNode helper(int left,int right){
    //遍历完成,则返回
        if(left==right)return null;
        //获取当前根节点
        int val=postorder[post_index];
        //获取中序遍历分叉点
        int mid=map.get(val);
        //往前遍历
        post_index--;
      	//创建结点
        TreeNode root=new TreeNode(val);
        //分治 递归
        root.right=helper(mid+1,right);
        root.left=helper(left,mid);
        
        return root;
    }
    
}

二叉树遍历(前序、中序、后序、层次遍历、深度优先、广度优先)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值