题解 | #重建二叉树#

重建二叉树

https://www.nowcoder.com/practice/8a19cbe657394eeaac2f6ea9b0f6fcf6

int ptr=0;
struct TreeNode* build(struct TreeNode* root,int* preOrder,int* vinOrder,int front,int rear)
{
    if(front>rear) return NULL;
    root=malloc(sizeof(struct TreeNode));
    root->val=preOrder[ptr++];
    int i=front;
    for(;i<rear;i++) if(vinOrder[i]==root->val) break;
    root->left=build(root->left,preOrder,vinOrder,front,i-1);
    root->right=build(root->right,preOrder,vinOrder,i+1,rear);
    return root;
}

struct TreeNode* reConstructBinaryTree(int* preOrder, int preOrderLen, int* vinOrder, int vinOrderLen ) {
    int front=0,rear=vinOrderLen-1;
    struct TreeNode* root;
    return build(root,preOrder,vinOrder,front,rear);
}

全部评论

相关推荐

我见java多妩媚:大外包
点赞 评论 收藏
分享
1 收藏 评论
分享
牛客网
牛客企业服务