• 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);
        }
    }
  • 相关阅读:
    链表的逆置(无聊而写)
    C
    大型分布式站点的技术需求
    leetcode第一刷_Best Time to Buy and Sell Stock
    微商行业面临洗礼,微盟萌店是否能完毕“神补刀”?
    oracle函数 CONCAT(c1,c2)
    oracle函数 CHR(n1)
    oracle函数 ASCII(x1)
    oracle函数 INTERVAL c1 set1
    oracle函数 SESSIONTIMEZONE
  • 原文地址:https://www.cnblogs.com/xxxxxiaochuan/p/13288267.html
Copyright © 2020-2023  润新知