其他分享
首页 > 其他分享> > leetcode 889. 根据前序和后序遍历构造二叉树

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

作者:互联网

思路

之前已经写过了根据后序和中序遍历构造二叉树,同理,根据前序和中序遍历构造二叉树的题目也可以写了,所以我没再写一次思路。889这题和前面的思路本质上也没有差别,都是想方法把树分成根,左子树和右子树,再分别递归

代码

/**
 * 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* constructFromPrePost(vector<int>& pre, vector<int>& post) {
        if(pre.size() == 0 && post.size() == 0)
            return NULL;
        TreeNode* root = new TreeNode(*(post.end()-1));
        if(pre.size() == 1 && post.size() == 1)
            return root;
        post.pop_back();
        vector<int>::iterator it_post = find(post.begin(), post.end(), *(pre.begin() + 1));
        vector<int>::iterator it_pre = find(pre.begin(), pre.end(), *(post.end()-1));
        // cout << "it_post: " << *it_post << ", it_pre: " << *it_pre << endl;
        vector<int> post_left(post.begin(), it_post+1);
        // for(int i = 0; i < post_left.size(); i++){
        //     cout << post_left[i] << ' ';
        // }
        // cout << endl;
        vector<int> post_right(it_post+1, post.end());
        // for(int i = 0; i < post_right.size(); i++){
        //     cout << post_right[i] << ' ';
        // }
        // cout << endl;
        vector<int> pre_left(pre.begin()+1, it_pre);
        // for(int i = 0; i < pre_left.size(); i++){
        //     cout << pre_left[i] << ' ';
        // }
        // cout << endl;
        vector<int> pre_right(it_pre,pre.end());
        // for(int i = 0; i < pre_right.size(); i++){
        //     cout << pre_right[i] << ' ';
        // }
        // cout << endl;
        if(pre_left.size() != 0 && post_left.size() != 0){
            root->left = constructFromPrePost(pre_left, post_left);
            root->right = constructFromPrePost(pre_right, post_right);
        }
        else{
            root->right = constructFromPrePost(pre_left, post_right);
            root->left = constructFromPrePost(pre_right, post_left);
        }
        return root;
    }
};

标签:pre,right,TreeNode,前序,二叉树,post,size,889,left
来源: https://blog.csdn.net/skywuuu/article/details/115390336