树和二叉树程序.docx





《树和二叉树程序.docx》由会员分享,可在线阅读,更多相关《树和二叉树程序.docx(7页珍藏版)》请在淘文阁 - 分享文档赚钱的网站上搜索。
1、树和二叉树常用算法创建二叉树 struct node char data; struct node *lchild,*rchild; ; void precreate(struct node *T) /先序、中序、后序递归建树遍历二叉树 void inorder(struct node *p)/中序遍历 if(p!=NULL) inorder(p-lchild); printf(%c ,p-data); inorder(p-rchild); 统计二叉树中叶子节点数 int leaf(NODE *t) if(t=NULL) return(0);else if(t-lchild=NULL&t-rc
2、hild=NULL) return(leaf(t-lchild)+leaf(t-rchild)+1);elsereturn(leaf(t-lchild)+leaf(t-rchild);统计二叉树中度为1的节点数 int num=0;void count(NODE *p) if(p!=NULL)count(p-lchild);if(p-lchild!=NULL&p-rchild=NULL|p-lchild=NULL&p-rchild!=NULL)num+;count(p-rchild);统计二叉树度为1的结点数方法2 int onechild(NODE *t) int num1,num2;if(
3、t=NULL) return(0);else if(t-lchild=NULL&t-rchild!=NULL|t-lchild!=NULL&t-rchild=NULL)return(onechild(t-lchild)+onechild(t-rchild)+1);elsenum1=onechild(t-lchild);num2=onechild(t-rchild);return(num1+num2);非递归统计出二叉树共有多少个度为1的结点 int onechild3(NODE *root) NODE *p,*s100;int top=0,num=0; /top为栈顶指针p=root;whil
4、e(p!=NULL)|(top0) while(p!=NULL)if(p-lchild!=NULL&p-rchild=NULL |p-lchild=NULL&p-rchild!=NULL)num+;s+top=p; p=p-lchild; p=stop-; p=p-rchild; return num;统计二叉树中所有节点数 int sum(NODE *t) if(t=NULL) return(0);else return(sum(t-lchild)+sum(t-rchild)+1);非递归二叉树前序遍历 Status PreOrderTraverse(BiTree T)Stack S;Ini
5、tStack(S);p=T;While(p|!StackEmpty(S)if(p) Visit(p-data);Push(S,p);p=p-lchild;elsePop(S,p);p=p-rchild;return SUCCESS;非递归二叉树中序遍历 Status InOrderTraveser(BiTree T)Stack S;InitStack(S);p=T;While(p|!StackEmpty(S)if(p)Push(S,p);p=p-lchild;else Pop(S,p);Visit(p-data);p=p-rchild;return SUCCESS非递归二叉树后序遍历 Stat
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- 二叉 程序

限制150内