zoukankan      html  css  js  c++  java
  • 105. Construct Binary Tree from Preorder and Inorder Traversal

    Given preorder and inorder traversal of a tree, construct the binary tree.

    Note:
    You may assume that duplicates do not exist in the tree.

    For example, given

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

    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[] preorder, int[] inorder) {
            if(preorder == null || inorder == null || preorder.length == 0 || preorder.length != inorder.length) {
                return null;
            }
            return buildTree(preorder, inorder, 0, 0, inorder.length - 1);
        }
        
        public TreeNode buildTree(int[] preorder, int[] inorder, int pre_start, int in_start, int in_end) {
            if(pre_start > preorder.length - 1 || in_start > in_end) {
                return null;
            }
            TreeNode root = new TreeNode(preorder[pre_start]);
            int idx = 0;
            for(int i = in_start; i <= in_end; i++) {
                if(inorder[i] == preorder[pre_start]) {
                    idx = i;
                }
            }
            
            root.left = buildTree(preorder, inorder, pre_start + 1, in_start, idx - 1);
            root.right = buildTree(preorder, inorder, pre_start + (idx - in_start + 1), idx + 1, in_end);
            
            return root;
        }
    }
  • 相关阅读:
    jquery 不支持$.browser
    js 双向绑定
    css3 省略号
    js生成txt文件
    Browser-sync
    Generator & yield write in sync way
    Charles
    缓动函数与动画
    让Safari使用Chrome的代理
    React 同构
  • 原文地址:https://www.cnblogs.com/fatttcat/p/10203056.html
Copyright © 2011-2022 走看看