写一个非递归遍历函数,计算二叉树的叶结点数.

来源:百度知道 编辑:UC知道 时间:2024/06/28 22:49:29

#include<stdio.h>
typedef struct node{char data;
struct node *rchild,*lchild;
}node,*bintree;
void creat(bintree *tree)/*建树*/
{char ch;
if((ch=getchar())==' ')*tree=NULL;
else {*tree=(bintree)malloc(sizeof(node));
(*tree)->data=ch;
creat(&(*tree)->lchild);
creat(&(*tree)->rchild);
}
}
int preorder2(bintree tree)/*非递归前序遍历*/
{bintree stack[30];int top=-1,count=0;
while(tree||top>-1)
{while(tree)
{ count++;
stack[++top]=tree;
tree=tree->lchild;
}
if(top>-1)
tree=stack[top--]->rchild;
}
return count;
}
void main()
{ bintree tree;
printf("creat tree:\n");
creat(&tree);
printf("%d",preorder2( tree));
getch();
}
/*利用树的非递归前序遍历做的*/