剑指--重建二叉树

来源:互联网 发布:mac 鼠标 触摸板 编辑:程序博客网 时间:2024/05/22 17:13

题目描述

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

class Solution {public:    struct TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> in) {        return reConstructBinaryTree(pre,0,pre.size()-1,in,0,in.size()-1);    }    TreeNode* reConstructBinaryTree(vector<int> &pre,int st_pre,int end_pre,vector<int> &in,int st_in,int end_in){        if(st_pre>end_pre)            return NULL;        TreeNode* root=new TreeNode(pre[st_pre]);        //找到根节点位置        int i=st_in;        for(;i<=end_in;i++)            if(in[i]==pre[st_pre])break;        //区别左右子树递归        root->left=reConstructBinaryTree(pre,st_pre+1,st_pre+i-st_in,in,st_in,i-1);        root->right=reConstructBinaryTree(pre,st_pre+i-st_in+1,end_pre,in,i+1,end_in);        return root;    }};


0 0