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

    time: O(nlogn) ~ O(n^2), space: O(height)

    /**
     * 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) {
            if(inorder == null || postorder == null || inorder.length == 0 || inorder.length != postorder.length) {
                return null;
            }
            return buildTree(postorder, postorder.length - 1, inorder, 0, inorder.length - 1);
        }
        
        public TreeNode buildTree(int[] postorder, int post_start, int[] inorder, int in_start, int in_end) {
            if(post_start < 0 || in_start > in_end) {
                return null;
            }
            TreeNode root = new TreeNode(postorder[post_start]);
            int idx = 0;
            for(int i = in_start; i <= in_end; i++) {
                if(inorder[i] == postorder[post_start]) {
                    idx = i;
                    break;
                }
            }
    
            root.left = buildTree(postorder, post_start - (in_end - idx + 1), inorder, in_start, idx - 1);
            root.right = buildTree(postorder, post_start - 1, inorder, idx + 1, in_end);
            
            return root;
        }
    }
  • 相关阅读:
    Murano Weekly Meeting 2016.05.24
    Murano Weekly Meeting 2016.05.17
    Murano Weekly Meeting 2016.05.10
    python3.4 x86_64-linux-gnu-gcc Error
    初学makefile
    解决Spring JdbcTemplate调用queryForObject()方法结果集为空时报异常
    svn命令行使用
    jquery选中checkbox
    jstl core and jstl fn
    linux上的shutdown命令
  • 原文地址:https://www.cnblogs.com/fatttcat/p/10204151.html
Copyright © 2011-2022 走看看