889. Construct Binary Tree from Preorder and Postorder Traversal [Medium]

https://leetcode.com/problems/construct-binary-tree-from-preorder-and-postorder-traversal/

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.
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */

算法思路:

还是那一套,但不同的是,无法利用pre的根节点去分割post,所以答案有很多种,我们返回一个正确答案即可。

我们每次假设pre中根节点的下一个节点是左子树的根节点,然后去post中进行分割,得到pre左子树个数和右子树个数,不断递归

举个例子:

  • pre:    1  2  4  5  3  6  7
  • post:   4  5  2  6  7  3  1

 

  • pre:    1  2  4  5  3  6  7
  • post:   4  5  2  6  7  3  1

 

  • pre:   1  2  4  5  3  6  7
  • post: 4  5  2  6  7  3  1

 

  • pre:   1    2  4  5      3  6  7
  • post:       4  5  2      6  7  3    1

 

  • pre:   1    2    4            3    6  7
  • post:             4  5    2           6  7    3    1

 

  • pre:   1    2    4    5           3    6    7
  • post:             4    5    2           6    7    3    1
class Solution {
public:
    TreeNode* constructFromPrePost(vector<int>& pre, vector<int>& post) {
        // pre: 根左右
        // post:左右根  有很多种答案
        int n = pre.size();
        return build(pre, 0, n - 1, post, 0, n - 1); 
    }
private:
    TreeNode* build(vector<int>& pre, int preStart, int preEnd, 
                    vector<int>& post, int postStart, int postEnd) {
        
        if (preStart > preEnd) return nullptr;
        TreeNode* node = new TreeNode(pre[preStart]);
        if (preStart == preEnd) return node;

        int i = postStart;
        for (; i <= postEnd; i++) {
            if (pre[preStart + 1] == post[i]) {
                break;
            }
        }
        int k = i - postStart + 1;
        
        node->left = build(pre, preStart + 1, preStart + k, post, postStart, i);
        node->right = build(pre, preStart + k + 1, preEnd, post, i + 1, postEnd - 1);
        
        return node;
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值