重建二叉树

来源:互联网 发布:adobe encoder mac 编辑:程序博客网 时间:2024/06/05 16:29

输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。

class Solution {public:    TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin) {        if (pre.size() < 0 || vin.size() <0 || pre.size() != vin.size())        {            return NULL;        }        return reConstructBinaryCore(pre, 0, pre.size()-1,vin, 0,vin.size()-1);    }    TreeNode*  reConstructBinaryCore(vector<int> pre,int startPre,int endPre, vector<int> vin,int startIn, int endIn)    {        int rootvalue = pre[startPre];        TreeNode* root = new TreeNode(rootvalue);        int InRoot = startIn;        while (InRoot <= endIn && vin[InRoot] != rootvalue)        {            InRoot++;        }        int leftlenth = InRoot - startIn;        if (leftlenth > 0)        {            root->left = reConstructBinaryCore(pre, startPre + 1, startPre + leftlenth, vin, startIn, startIn + leftlenth - 1);        }        if (endPre - startPre >leftlenth)        {            root->right = reConstructBinaryCore(pre, startPre + leftlenth + 1, endPre, vin,startIn + leftlenth + 1, endIn);        }        return root;    }};