2014-12-08 19 views
0

功能从构建树序和预购无法理解这个代码的最后一步

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);

+1

你究竟知道些什么?语法?逻辑?请更具体一些。 – Maroun 2014-12-08 08:57:44

+1

它递归地调用该函数。 – 2014-12-08 08:59:45

+0

@MarounMaroun逻辑不清楚,因为后手调试我发现i和num的值将在某一步是相同的,并且不会是终止的基本情况我在数据结构书中发现此代码 – yogeshmanjhi 2014-12-08 09:01:22

回答

0

达到什么做Inorder is [Lin]N[Rin] and Preorder is N[Lpr][Rpr]

该函数挑选从预订第一节点N1和N后从列表中序构建左subchild(与序的助剂),并从中序列表(与序的助剂)右subchild

该代码实现这一点通过下面的中止条件递归

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

关于一步,你不明白
for(j=1;j<=i+1;j++) preptr=preptr->next;将推动preptr超越N和[LPR],然后在接下来的步骤是用来构造右子TR EE。它使用for(i=q;q->info!=preptr->info;i++) q=q->next;之前的步骤计算左子树中节点的数量。所以,当你调用该函数revursively:

Q->未来指向[凛]
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

+0

可以请你给我的代码来测试上述功能,以便我可以检查它的调试 – yogeshmanjhi 2014-12-08 09:29:08

+0

@ mohit非常感谢我现在了解它! – yogeshmanjhi 2014-12-08 09:36:47

+0

我很高兴它帮助你:) – 2014-12-08 09:47:07