无法理解此代码的最后一步
unable to understand the last step in this code
用于从无序和预序构造树的函数
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
相关文章:
- 维护unordered_map但同时每一步都需要最低的映射值
- 如何在最后一步使用CryptDecrypt解决NTE_BAD_DATA
- 如何检测是否在缓冲绘画动画中绘制最后一帧?
- 斐波那契数列部分和的最后一位数字
- std::ifstream 在读取文件中最后一项时设置 eofbit,但仅在读取数值类型时发生
- 将第 n 个斐波那契数的大斐波那契数的最后一位编程.C++
- 如何在 C++ 中返回到上一步
- 经过最后一个数组元素末尾的指针是否应该等于超过整个数组末尾的指针?
- foor 循环的最后一次迭代中的指针更改
- 访问类成员向量最后一项的正确方法
- 从函数参数包中删除最后一项
- 如何一步一步地正确解释此代码?(编程新手)
- 将隐式促销添加到复杂类,最后一步
- 如何在Linux / Windows操作系统上使用文件*.cpp一步编译下面的代码
- 我在spoj-lastdig2中使用我的代码 - 重新访问的最后一位数字
- 有没有一个调试器可以让我在代码中后退一步
- 我在一个简单控制台程序(c++)中的第一列代码最终成为我的最后一列
- 无法理解此代码的最后一步
- 只有当我在 c++ 中按 Enter 键(线程)时,代码如何进入下一步
- 这是否C++代码交换第一个和最后一个位