首页 > 其他 > 详细

106. 从中序与后序遍历序列构造二叉树-中等难度

时间:2020-07-12 15:24:53      阅读:50      评论:0      收藏:0      [点我收藏+]

问题描述

根据一棵树的中序遍历与后序遍历构造二叉树。

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

例如,给出

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

3
/ \
9 20
/ \
15 7

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal

解答

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    int[] postorder2 = null;
    int[] inorder2 = null;
    Map<Integer,Integer> map = null;
    int len = 0;
    public TreeNode recursive(int inorder_left,int inorder_right,int postorder_left,int postorder_right){
        if(inorder_right-inorder_left<=0)return null;
        if(inorder_right-inorder_left==1)return new TreeNode(inorder2[inorder_left]);
        int position = map.get(postorder2[postorder_right-1]);
        TreeNode r = null;
        if(position+1<len)
        r = recursive(position+1,inorder_right,postorder_right-(inorder_right-position),postorder_right-1);
        TreeNode l = recursive(inorder_left,position,postorder_left,postorder_left+position-inorder_left);
        return new TreeNode(postorder2[postorder_right-1],l,r);
    }
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        len = inorder.length;
        if(len==0)return null;
        postorder2 = postorder;
        inorder2 = inorder;
        map = new HashMap<Integer,Integer>();
        for(int i=0;i<len;i++)
            map.put(inorder2[i],i);
        return recursive(0,len,0,len);
    }
}

 

106. 从中序与后序遍历序列构造二叉树-中等难度

原文:https://www.cnblogs.com/xxxxxiaochuan/p/13288267.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!