数据结构——补充二叉树的一些算法程序
1.以二叉链表为存储结构,编写算法交换每个结点的左右子树。
void Swap(BinTree bt) { BinTree t; if(bt->lchild!=NULL&&bt->rchild!=NULL) { Swap(bt->lchild); Swap(bt->rchild); t=bt->lchild; bt->lchild=bt->rchild; bt->rchild=t; } }
2.以二叉链表为存储结构,编写算法求出二叉树中度为1的结点个数。
counts=0; void Count(BinTree bt,int *counts) { if(bt->lchild!=NULL&&bt->rchild==NULL) { counts++; } else if(bt->rchild!=NULL&&bt->lchild==NULL) { counts++; } Count(bt->lchild,counts); Count(bt->rchild,counts); }
ps:这个思路参考求二叉树叶子结点的那个代码来的。
3.以二叉链表为存储结构,编写算法求二叉树中结点x的双亲
void FindPr(BinTree bt,BinTree *P,char x) { if(bt) { if(bt->lchild!=NULL) { if(bt->lchild->data==x) { p=bt; return ; } } else if(bt->rchild!=NULL) { if(bt->rchild->data==x) { p=bt; return ; } } FindPr(bt->lchild,x); FindPr(bt->rchild,x); } }
4.以二叉链表为存储结构,编写算法复制一棵二叉树
void Copy(BinTree bt,BinTree *s) { BinTree lptr, rptr; if(!bt)//bt=NULL { s=NULL; } else { Copy(bt->lchild,lptr); Copy(bt->rchild,rptr); s=(BiTree*)malloc(sizeof(BiTree) ); s->data=bt->data; s->lchild=lptr; s->rchild=rptr; } }
本文作者:王陸
本文链接:https://www.cnblogs.com/wkfvawl/p/10065290.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
分类:
数据结构课程
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步