我被要求写迭代版本,但我写了递归版本,即:
void inorderTraverse(BinaryTree root)
{
if(root==NULL)
printf("%d",root->id);
else
{
inorderTraverse(root->left);
printf("%d",root->id);
inorderTraverse(root->right);
}
}
我不是在寻找代码,而是想要理解这个如何完成。如果只是最后一次递归调用,我会做的。
void inorderTraverse(BinaryTree root)
{
while(root!=NULL)
{
printf("%d",root->id);
root=root->right;
}
}
但是,当有两个递归调用时,我该如何转换成迭代程序?
以下是类型定义。
struct element{
struct element* parent;
int id;
char* name;
struct element* left;
struct element* right;
};
typedef element* BinaryTree;
这是我的想法,我走在正确的道路上吗?
temp=root;
while(1)
{
while(temp!=NULL)
{
push(s,temp);
temp=temp->left;
continue;
}
temp=pop(s);
if(temp==NULL)
return;
printf("%d\t",temp->data);
temp=temp->right;
}
BinaryTree
接口吗?获取树节点的父节点是否可行? - Arnout Engelen