LeetCode Construct Binary Tree from Inorder and Postorder Traversal

本文介绍了一种使用Inorder和Postorder遍历构建二叉树的方法,并提供了一个Java实现示例。该算法的时间复杂度为O(n),空间复杂度也为O(n)。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原题链接在这里:https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/

这道题与Construct Binary Tree from Preorder and Inorder Traversal 思路相似,不同之处在于这里的root在postorder的最有一位,其他都相同,由inorder找出分切点。

Time O(n), Space O(n).

Note: 在recursion调用时postorder的index更新一定会用到(index-inL). 我刚开始很凑巧的写成了postR = index-1, 第一次循 环恰巧相等,但之后就不对了。

AC Java:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        if(inorder == null || postorder == null || inorder.length == 0|| postorder.length == 0 || inorder.length != postorder.length){
            return null;
        }
        HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();
        for(int i = 0; i< inorder.length; i++){
            hm.put(inorder[i],i);
        }
        return helper(inorder, 0, inorder.length-1, postorder, 0, postorder.length-1, hm);
    }
    private TreeNode helper(int[] inorder,int inL,int inR, int[] postorder,int postL,int postR, HashMap<Integer, Integer> hm){
        if(inL>inR || postL>postR){
            return null;
        }
        TreeNode root = new TreeNode(postorder[postR]);
        int index = hm.get(root.val);
        root.left = helper(inorder, inL, index-1, postorder, postL, index-inL+postL-1, hm); //error
        root.right = helper(inorder, index+1, inR, postorder, index-inL+postL, postR-1, hm);
        return root;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值