889. Construct Binary Tree from Preorder and Postorder Traversal - Medium

Posted fatttcat

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了889. Construct Binary Tree from Preorder and Postorder Traversal - Medium相关的知识,希望对你有一定的参考价值。

Return any binary tree that matches the given preorder and postorder traversals.

Values in the traversals pre and post are distinct positive integers.

 

Example 1:

Input: pre = [1,2,4,5,3,6,7], post = [4,5,2,6,7,3,1]
Output: [1,2,3,4,5,6,7]

 

Note:

  • 1 <= pre.length == post.length <= 30
  • pre[] and post[] are both permutations of 1, 2, ..., pre.length.
  • It is guaranteed an answer exists. If there exists multiple answers, you can return any of them.

 

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 constructFromPrePost(int[] pre, int[] post) {
        return buildTree(pre, 0, pre.length - 1, post, 0, post.length - 1);
    }
    
    public TreeNode buildTree(int[] pre, int pre_start, int pre_end, int[] post, int post_start, int post_end) {
        if(pre_start > pre_end || post_start > post_end) {
            return null;
        }
        
        TreeNode root = new TreeNode(pre[pre_start]);
        if(pre_start + 1 > pre_end) {
            return root;
        }
        
        int idx = 0;
        for(int i = post_start; i <= post_end; i++) {
            if(post[i] == pre[pre_start + 1]) {
                idx = i;
                break;
            }
        }
        
        root.left = buildTree(pre, pre_start + 1, pre_start + idx - post_start + 1, post, post_start, idx);
        root.right = buildTree(pre, pre_start + idx - post_start + 2, pre_end, post, idx + 1, post_end - 1);
        
        return root;
    }
}

 

以上是关于889. Construct Binary Tree from Preorder and Postorder Traversal - Medium的主要内容,如果未能解决你的问题,请参考以下文章

(二叉树 递归) leetcode 889. Construct Binary Tree from Preorder and Postorder Traversal

[LeetCode] 889. Construct Binary Tree from Preorder and Postorder Traversal 由先序和后序遍历建立二叉树

Construct Binary Tree from Preorder and Inorder Traversal

889. 根据前序和后序遍历构造二叉树

889. 根据前序和后序遍历构造二叉树

889. 根据前序和后序遍历构造二叉树(非递归)