【Leetcode】106. Construct Binary Tree from Inorder and Postorder Traversal

106. Construct Binary Tree from Inorder and Postorder Traversal

Given inorder and postorder traversal of a tree, construct the binary tree.

Note:
You may assume that duplicates do not exist in the tree.

Subscribe to see which companies asked this question.

题目简述:

输入中序遍历和后序遍历的数组,要求重构二叉树并返回二叉树根节点。

思路分析:

1.前序遍历,中序遍历和后序遍历只要知道中序遍历加其他任意一个能唯一确定一棵二叉树

2.使用Hash表建立中序遍历的索引,让时间复杂度从O(N^2)->O(N).空间复杂度O(1)->O(N)

复杂度:

时间复杂度O(N)

空间复杂度O(N)

代码:

public class Solution {
    int count;
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        TreeNode aNode =null;
        if(inorder.length == 0){
            return null;
        }else{
            aNode =new TreeNode(postorder[postorder.length-1]);
            //aNode.val = ;
        }
        Map<Integer,Integer> aMap = createIndex(inorder);
        count = inorder.length-2;
        //传入的部分都是未使用过的元素
        aNode.right = createSubTree(aMap.get(aNode.val)+1,inorder.length-1,postorder,aMap);
        aNode.left = createSubTree(0,aMap.get(aNode.val)-1,postorder,aMap);
        return aNode;
    }
    
    public TreeNode createSubTree(int start,int end,int[] postorder,Map<Integer,Integer> aMap){
        if(start>end){
            return null;
        }
        TreeNode aNode = new TreeNode(postorder[count--]);
        aNode.right = createSubTree(aMap.get(aNode.val)+1,end,postorder,aMap);
        aNode.left = createSubTree(start,aMap.get(aNode.val)-1,postorder,aMap);
        return aNode;
    }
    public Map<Integer,Integer> createIndex(int[] inorder){
        Map<Integer,Integer> aMap =new HashMap<>();
        for(int i=0;i<inorder.length;i++){
            aMap.put(inorder[i],i);
        }
        return aMap;
    }
}

结果:

65%

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值