重建二叉樹

題目描述

輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。例如輸入前序遍歷序列{1,2,4,7,3,5,6,8}和中序遍歷序列{4,7,2,1,5,3,8,6},則重建二叉樹並返回。

#include <iostream>

#include <vector>

using namespace::std;

struct TreeNode{

    int val;

    TreeNode*left;

    TreeNode*right;

    TreeNode(int x):val(x),left(NULL),right(NULL){}

};


class Solution {

public:

    struct TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> in) {

        if(pre.size() == 0 || in.size()==0) return NULL;

        TreeNode*root = new TreeNode(pre[0]);

        vector<int>Leftpre;

        vector<int>Leftint;

        vector<int>Rightpre;

        vector<int>Rightint;

        int i = 1;

        int k = 0;

        for( i = 1; i < pre.size(); i++){

            if(in[i-1] == pre[0]){

                Leftpre.push_back(pre[i]);

                break;

            }

    

            Leftpre.push_back(pre[i]);

            Leftint.push_back(in[i-1]);

        }

        

        for(int j = i; j < in.size(); j++){

            Rightpre.push_back(pre[j]);

            Rightint.push_back(in[j]);

        }

        root->left = reConstructBinaryTree(Leftpre, Leftint);

        root->right = reConstructBinaryTree(Rightpre, Rightint);

        return root;

        

    }

};


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