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;
        }
    }
  • 相关阅读:
    markdown语法及工具
    关于div的宽度或高度设置为100%时
    响应式css垂直居中
    JavaScript之闭包问题以及立即执行函数
    JavaScript和JQuery好书推荐
    数组中去重
    解决getImageData跨域问题
    js在for循环中绑定事件
    表格横竖颠倒
    上传按钮美化遇到的问题
  • 原文地址:https://www.cnblogs.com/fatttcat/p/10204151.html
Copyright © 2011-2022 走看看