zoukankan      html  css  js  c++  java
  • 106. 从中序与后序遍历序列构造二叉树-中等难度

    问题描述

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

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

    例如,给出

    中序遍历 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);
        }
    }
  • 相关阅读:
    2020年蓝桥杯校内模拟赛
    kaggle入门——泰坦尼克之灾
    在线程池里面执行
    如何使用在线工具手动验证JWT签名
    python日志模块
    性能测试
    自动生成时间
    jmeter + tomcat + ant + svn +jenkins 实现持续集成测试
    JMeter性能测试,完整入门篇
    jmeter 24个常用函数
  • 原文地址:https://www.cnblogs.com/xxxxxiaochuan/p/13288267.html
Copyright © 2011-2022 走看看