重建二叉树

题目描述

输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{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;

        

    }

};


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