Skip to content

Latest commit

 

History

History
 
 

889. Construct Binary Tree from Preorder and Postorder Traversal

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 

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.

Companies:
Google, Bloomberg

Related Topics:
Tree

Solution 1.

// OJ: https://leetcode.com/problems/construct-binary-tree-from-preorder-and-postorder-traversal/
// Author: github.com/lzl124631x
// Time: O(N^2)
// Space: O(N)
class Solution {
private:
    TreeNode *construct(vector<int> &pre, int preBegin, int preEnd,
                       vector<int> &post, int postBegin, int postEnd) {
        if (preBegin >= preEnd) return NULL;
        auto node = new TreeNode(pre[preBegin]);
        if (preBegin + 1 < preEnd) {
            int leftVal = pre[preBegin + 1];
            int postMid = find(post.begin() + postBegin, post.begin() + postEnd - 1, leftVal) - post.begin();
            int postLeftLength = postMid - postBegin + 1;
            node->left = construct(pre, preBegin + 1, preBegin + 1 + postLeftLength,
                                   post, postBegin, postMid + 1);
            node->right = construct(pre, preBegin + 1 + postLeftLength, preEnd,
                                   post, postMid + 1, postEnd - 1);
        }
        return node;
    }
public:
    TreeNode* constructFromPrePost(vector<int>& pre, vector<int>& post) {
        return construct(pre, 0, pre.size(), post, 0, post.size());
    }
};