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

返回与给定的前序和后序遍历匹配的任何二叉树。

 pre 和 post 遍历中的值是不同的正整数。

 

示例:

输入:pre = [1,2,4,5,3,6,7], post = [4,5,2,6,7,3,1]
输出:[1,2,3,4,5,6,7]
 

提示:

1 <= pre.length == post.length <= 30
pre[] 和 post[] 都是 1, 2, ..., pre.length 的排列
每个输入保证至少有一个答案。如果有多个答案,可以返回其中一个。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-postorder-traversal
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* constructSubTree(vector<int>& pre, int preStart, int preEnd, vector<int>& post, int postStart, int postEnd)
    {
        if(preStart > preEnd || postStart > postEnd)
        {
            return NULL;
        }
        TreeNode* node =  new TreeNode(pre[preStart]);
        
        if(preStart == preEnd)
        {
            return node;
        }

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

    }

    TreeNode* constructFromPrePost(vector<int>& pre, vector<int>& post) {        
        int len = pre.size();
        if(len == 0)
        {
            return NULL;
        }
        return constructSubTree(pre, 0, len-1, post, 0, len-1);
    }
};

  

posted @ 2021-09-01 22:02  linqiaozhou  阅读(66)  评论(0编辑  收藏  举报