Construct Binary Tree from Preorder and Inorder Traversal

来源:互联网 发布:java工厂模式优缺点 编辑:程序博客网 时间:2024/06/05 11:50

常见的根据前序遍历和中序遍历构造二叉树

根据前序遍历可以知道根节点。找到这个数字在中序遍历中出现的位置,这个数字便是这颗子树的根,这个位置之前的在根的左边,这个位置之后的在根的右边。


class Solution {    TreeNode *build(vector<int> &pre, vector<int> &in, int s,int e,int &p)    {        if(s>e)            return NULL;        int dir=-1;        for(int i=s;i<=e;i++)            if(in[i]==pre[p])                dir=i;        //system("pause");        TreeNode *t=new TreeNode(pre[p++]);        t->left=build(pre,in,s,dir-1,p);        t->right=build(pre,in,dir+1,e,p);        return t;    }public:    TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {        int p =0;        return build(preorder,inorder,0, inorder.size()-1,p);    }};


0 0
原创粉丝点击