Leetcode106. 从中序与后序遍历序列构造二叉树Construct Binary Tree from Inorder and Postorder Traversal(Java)

Leetcode106. 从中序与后序遍历序列构造二叉树Construct Binary Tree from Inorder and Postorder Traversal(Java)

##Array##, ##Tree##, ##Depth-first Tree##

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

Leetcode.105 从前序与中序遍历序列构造二叉树类似,采用递归做法,创建根节点,递归创建左右子树,根节点连接左右子树

  • 利用后序遍历的性质,前序遍历的最后一个数就是根节点的值
  • 在中序遍历中按根节点的值找到根节点的位置temp,则temp左边时左子树的中序遍历,右边是右子树的中序遍历
  • 不妨设左子树中序遍历的长度为len1,则在后序遍历中,后序遍历左端pl后面的len1个数,是左子树的前序遍历,剩余右边的数是右子树的前序遍历(除最后位置pr的根节点的值),
  • 有了左右子树的前序遍历和中序遍历,便可以递归创建左右子树,最后与根节点相连
  • 可以用哈希表将中序遍历的值和位置作映射,这样在中序遍历中招根节点时时间复杂度变为O(1)
  • 一定考虑递归出口pl > pr || il > ir

**时间复杂度:**O(n)

class Solution {
    int[] ino, posto;
    int m, n;
    HashMap<Integer, Integer> hash = new HashMap<>();
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        ino = inorder;
        posto = postorder;
        m = ino.length;
        n = posto.length;
        if (m == 0) return null;
        for (int i = 0; i < m; i ++) {
            hash.put(inorder[i], i);
        }
        return helper(0, m - 1, 0, n - 1);
    }
    
    public TreeNode helper(int sino, int eino, int sposto, int eposto) {
        if (sino == eino) return new TreeNode(ino[sino]);//此行不必要,可加快程序运行速度
        if (sino > eino || sposto > eposto) return null;
        int temp = hash.get(posto[eposto]);
        TreeNode res = new TreeNode(ino[temp]);
        res.left = helper(sino, temp - 1, sposto, sposto + temp - sino - 1);
        res.right = helper(temp + 1, eino, sposto + temp - sino, eposto - 1);
        return res;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值