无法理解此代码的最后一步

unable to understand the last step in this code

本文关键字:代码 最后一步      更新时间:2023-10-16

用于从无序和预序构造树的函数

struct treenode * construct(struct listnode *inptr,struct listnode * preptr ,int num)
{    
    struct treenode *temp;
    struct listnode *q;
    int i,j;
    if(num==0)
    return NULL;
    temp=(struct treenode *)malloc(sizeof(struct treenode));
    temp->info=preptr->info;
    temp->left=NULL;
    temp->right=NULL;
    if(num==1)/*if only one node  in tree*/
    return temp;
    q=inptr;
    for(i=q;q->info!=preptr->info;i++) q=q->next;
    /*now q points to root node in inorder list and the number of nodes in its left tree is i*/
    /*for left subtree*/
    temp->lchild=construct(inptr,preptr->next,i);
    /*for right subtree*/
    for(j=1;j<=i+1;j++) preptr=preptr->next;
    temp->rchild=construct(q->next,preptr,num-i-1);//unbale to understand this step as after node G construction value of i and num would be same this would result in -1
    return temp;
}/*end of construct */

问题:我无法理解我们希望通过temp->rchild=construct(q->next,preptr,num-i-1);实现什么

Inorder 是 [Lin]N[Rin] 和 Preorder 是N[Lpr][Rpr]

此函数从预序中选取第一个节点 N,并从 Inorder 列表中构造左子子节点(借助预序),从 Inorder 列表中构造右子节点(借助预序)在 N 之后。

代码通过具有以下终止条件的递归来实现此目的

if(num==1)/*if only one node  in tree*/
    return temp;

关于您不理解
的步骤 for(j=1;j<=i+1;j++) preptr=preptr->next; 会将 preptr 推进到 N 和 [Lpr] 之外,在下一步中,它将用于构建正确的子树。它使用步骤for(i=q;q->info!=preptr->info;i++) q=q->next;信息,在该步骤之前计算左侧子树中的节点数。因此,当您重新调用该函数时:

q->next 指向 [Rin]
preptr 指向 [Rpr]
num-i-1 是右子树中的节点数

作为旁注
for(i=q;q->info!=preptr->info;i++) q=q->next;应该是for(i=0;q->info!=preptr->info;i++) q=q->next;.通知 q 替换为 0