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

265 篇文章 2 订阅
235 篇文章 0 订阅

leetcode 106 题 从中序与后序遍历序列构造二叉树

leetcode 106:从中序与后序遍历序列构造二叉树 原题链接
题目描述:

给定两个整数数组 inorder 和 postorder ,
其中 inorder 是二叉树的中序遍历,
postorder 是同一棵树的后序遍历,
请你构造并返回这颗 二叉树 。

示例:
在这里插入图片描述
输入:inorder = [9,3,15,20,7], postorder = [9,15,7,20,3]
输出:[3,9,20,null,null,15,7]

示例2:
输入:inorder = [-1], postorder = [-1]
输出:[-1]

提示:
1 <= inorder.length <= 3000
postorder.length == inorder.length
-3000 <= inorder[i], postorder[i] <= 3000
inorder 和 postorder 都由 不同 的值组成
postorder 中每一个值都在 inorder 中
inorder 保证是树的中序遍历
postorder 保证是树的后序遍历

解题思路

中序遍历: 左头右
后序遍历: 左右头
后序遍历的最后一个节点就是头节点,在中序遍历中刚好又把树分为左树和右树,
这就和根据前序和中序遍历构造二叉树是一样的了,
我们递归去构建这颗树就行了,

解题代码:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        return  process(inorder,0,inorder.length-1,postorder,0,postorder.length-1);
    }
    /**
    * 递归去组建树
    * is 是左子树起始位置,
    * ie 是左子树结束位置
    * ps 右子树起始位置
    * pe 右子树结束位置
    */
    public TreeNode process(int[]inorder,int is,int ie,int[]postorder,int ps,int pe){
    	//base case 
        if(is > ie || ps > pe){
            return null;
        }
        //根据后序遍历的头节点来去找中序遍历头节点位置,把数组分成左树和右树。
        int headVal = postorder[pe];
        int index = 0;
        for(int i = is; i <= ie;i++){
            if(inorder[i] == headVal){
                index = i;
                break;
            }
        }
        //左子树的长度
        int leftSize = index - is;
        TreeNode head = new TreeNode(headVal);
        head.left = process(inorder,is,index-1,postorder,ps,ps+leftSize-1);
        head.right = process(inorder,index+1,ie,postorder,ps+leftSize,pe-1);
        return head;
    }
}

二叉树专题

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

leetcode二叉树中的最大路径和

二叉树的序列化和反序列化

求两个节点的最低公共祖先

给定一棵二叉树的头节点,返回这颗二叉树中最大的二叉搜索子树的头节点

计算二叉树中最大的二叉搜索子树的大小(节点数量)

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值