题解 | #JZ4 重建二叉树#

重建二叉树

http://www.nowcoder.com/practice/8a19cbe657394eeaac2f6ea9b0f6fcf6

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin) {
        if(pre.size() == 0){
            return NULL;
        }

        if(pre.size() == 1){
             TreeNode* root = (TreeNode* )malloc(sizeof(struct TreeNode));
             root->val = pre[0];
             root->left = NULL;
             root->right = NULL;
             return root;
        }
        int rootValue = pre[0];
        TreeNode* root = (TreeNode* )malloc(sizeof(struct TreeNode));
        root->val = rootValue;
        int rootValuaInVinPos = -1;
        int leftTreeSize;
        int rightTreeSize;
        for(int i=0;i<vin.size();i++){
            if(vin[i] == rootValue){
                leftTreeSize = i;
                break;
            }
        }
        rightTreeSize = pre.size() - 1 - leftTreeSize;
        vector<int> leftPre;
        vector<int> leftVin;
        for(int i=0;i<leftTreeSize;i++){
            leftPre.push_back(pre[i+1]);
        }
        for(int i=0;i<leftTreeSize;i++){
            leftVin.push_back(vin[i]);
        }
        TreeNode* leftTree = reConstructBinaryTree(leftPre,leftVin);

        vector<int> rightPre;
        vector<int> rightVin;
        for(int i=0;i<rightTreeSize;i++){
            rightPre.push_back(pre[i+1+leftTreeSize]);
        }
        for(int i=0;i<rightTreeSize;i++){
            rightVin.push_back(vin[i+1+leftTreeSize]);
        }
        TreeNode* rightTree = reConstructBinaryTree(rightPre,rightVin);

        root->left = leftTree;
        root->right = rightTree;
        return root;
    }
};
全部评论

相关推荐

怎么起名字:学历不足,
点赞 评论 收藏
分享
嗷佛快来快来快快快来:我当时就是听了别人的谣言,环境的大变,左右摇摆不定,到最后一事无成。我也给你提不了什么有效的建议,因为我自己就是败犬。但是我确实是从cpp转到了Java,cpp也做过项目,了解过具体的细分方向。如果你感兴趣,不会拦你。因为只要一件事情能坚持下去 就会发光
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务