牛客-重建二叉樹

牛客-重建二叉樹


#include <stdio.h>
#include <queue>
#include <stack>
#include <math.h>
#include <map>
#include <string.h>
#include <string>
#include <cstring>
#include <set>
using namespace std;


 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 || vin.size()<=0 || pre.size()!=vin.size()) {
            return NULL;
        }
        TreeNode *root = new TreeNode(pre[0]);
        vector<int> leftPre, leftVin;
        vector<int> rightPre, rightVin;
        int rootValue=root->val;
        int indeOfRootInVin=0;
        for (int i=0; i<vin.size(); i++) {
            if (vin[i]==rootValue) {
                indeOfRootInVin=i;
                break;
            }
        }
        int lengthOfLeft=0;
        for (int j=0; j<vin.size(); j++) {
            if (j<indeOfRootInVin) {
                leftVin.push_back(vin[j]);
                lengthOfLeft++;
            } else if (j>indeOfRootInVin) {
                rightVin.push_back(vin[j]);
            }
        }
        
        for (int k=1; k<pre.size(); k++) {
            if (k<(1+lengthOfLeft)) {
                leftPre.push_back(pre[k]);
            } else {
                rightPre.push_back(pre[k]);
            }
        }
        
        root->left = reConstructBinaryTree(leftPre, leftVin);
        root->right = reConstructBinaryTree(rightPre, rightVin);
        
        return root;
    }
};

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章