重建二叉树

题目描述

输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
/**
 * 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)
    {
        int len=vin.size();
        if(len==0)
            return NULL;
        TreeNode* root=new TreeNode(pre[0]);
        vector<int> pre_left,pre_right,vin_left,vin_right;
        int rootpoint;
        for(int i=0; i<len; i++)
        {
            if(vin[i]==pre[0])
                rootpoint=i;
        }
        for(int i=0; i<rootpoint; i++)
        {
            vin_left.push_back(vin[i]);
            pre_left.push_back(pre[i+1]);
        }
        for(int j=rootpoint+1; j<len; j++)
        {
            vin_right.push_back(vin[j]);
            pre_right.push_back(pre[j]);
        }
        root->left=reConstructBinaryTree(pre_left,vin_left);
        root->right=reConstructBinaryTree(pre_right,vin_right);
        return root;
    }
    void pre(TreeNode* &root)
    {
        if(root==NULL)
            return;
        cout<<root->val<<" ";
        pre(root->left);
        pre(root->right);
    }
};

 

posted @ 2018-04-11 15:55  Lincy*_*  阅读(140)  评论(0编辑  收藏  举报