zoukankan      html  css  js  c++  java
  • [LC] 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.

    For example, given

    inorder = [9,3,15,20,7]
    postorder = [9,15,7,20,3]

    Return the following binary tree:

        3
       / 
      9  20
        /  
       15   7

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        public TreeNode buildTree(int[] inorder, int[] postorder) {
            Map<Integer, Integer> mymap = new HashMap<>();
            for (int i = 0; i < inorder.length; i++) {
                mymap.put(inorder[i], i);
            }
            return helper(0, inorder.length - 1, 0, postorder.length - 1, postorder, mymap);
        }
        
            private TreeNode helper(int inLeft, int inRight, int postLeft, int postRight, int[] postorder, Map<Integer, Integer> mymap) {
            if (inLeft > inRight) {
                return null;
            }
            TreeNode cur = new TreeNode(postorder[postRight]);
            int index = mymap.get(postorder[postRight]);
            int leftSize = index - inLeft;
            // postRight for left just add up leftSize
            cur.left = helper(inLeft, index - 1, postLeft, postLeft + leftSize - 1, postorder, mymap);
            cur.right = helper(index + 1, inRight, postLeft + leftSize, postRight - 1, postorder, mymap);
            return cur;
        }
    }
  • 相关阅读:
    Eclipse护眼技巧
    Maven搭建SSM框架(Spring+SpringMVC+MyBatis)
    Spring之各jar包作用
    Maven新建web项目jsp报错
    js金额转大写(万元为单位)
    linux常用指令
    ie8下数组不支持indexOf方法解决方法
    string,stringBuffer,stringBuilder的比较
    input限制输入
    spring boot Mybatis --maven
  • 原文地址:https://www.cnblogs.com/xuanlu/p/12170929.html
Copyright © 2011-2022 走看看