美文网首页
construct-binary-tree-from-preor

construct-binary-tree-from-preor

作者: DaiMorph | 来源:发表于2019-05-24 21:39 被阅读0次
    class Solution {
    public:
        TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
            return create(preorder,inorder,0,preorder.size()-1,0,inorder.size()-1);
        }
        TreeNode *create(vector<int>pre,vector<int>in,int preL,int preR,int inL,int inR)
        {
            if(preL>preR)return NULL;
            TreeNode*root=new TreeNode(pre[preL]);
            int k;
            for(k=inL;k<=inR;k++){if(in[k]==root->val)break;}
            int numleft=k-inL;
            root->left=create(pre,in,preL+1,preL+numleft,inL,k-1);
            root->right=create(pre,in,preL+numleft+1,preR,k+1,inR);
            return root;
        }
    };
    

    相关文章

      网友评论

          本文标题:construct-binary-tree-from-preor

          本文链接:https://www.haomeiwen.com/subject/lytozqtx.html