算法题-从中序和后序遍历序列构造二叉树

题目链接:https://leetcode-cn.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/
题目描述:根据一棵树的中序遍历与后序遍历构造二叉树。

注意:
你可以假设树中没有重复的元素。

例如,给出

中序遍历 inorder = [9,3,15,20,7]
后序遍历 postorder = [9,15,7,20,3]
返回如下的二叉树:

    3
   / \
  9  20
    /  \
   15   7
解答

通过递归建立二叉树
时间复杂度:O(N),空间复杂度:O(N)

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    //rootIndex表示每次从postorder中获得的根结点的下标
    int rootIndex ;
    //indexMap 中存储inorder中的值和它们的下标的对应关系
    Map<Integer,Integer> indexMap = new HashMap<>();
    public TreeNode buildTree(int[] inorder, int[] postorder) {  
        //判断临界条件
        if(inorder == null || postorder ==null || inorder.length<=0 || postorder.length<=0){
            return null;
        }   
        //将inorder中的值和它们的下标的对应关系存入map 
        for(int i=0;i<inorder.length;i++){
            indexMap.put(inorder[i],i);
        }
        //从后序遍历数组的最后一个元素开始,是第一个根结点
        rootIndex = postorder.length-1;
        //调用helper来建立二叉树
        return helper(inorder,postorder,0,postorder.length-1);
    }
    public TreeNode helper(int[] inorder,int[] postorder,int left,int right) {
        //终止条件
        if(left>right) {
            return null;
        } 
        //当前层做的事情
        //新建一个结点存储遍历到的根结点       
        TreeNode root = new TreeNode(postorder[rootIndex]);
        //获取这个根结点在inorder中的下标index
        int index = indexMap.get(postorder[rootIndex]);
        //rootIndex减1,指向下一个要找的根结点
        rootIndex--;
        //下一层要做的事情
        //根据index将inorder分成右部分和左部分,分别对应右子树和左子树
        root.right=helper(inorder,postorder,index+1,right);
        root.left = helper(inorder,postorder,left,index-1);
        return root;
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值