一个月没更新博客了
1.二叉数的二叉链表储存表示
typedef struct BiTNode
{
char data;
struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;
为了方便自己记忆,以及和前面学到的链表、栈、队列区分定义结构体(前面定义的结构体不需要写)*LinkList
,他们(链表、栈、队列)只需要写LNode
,就可以操作了,二叉树不行,二叉树需要用到二级指针,但是为什么用二级指针我现在还没有理解,等以后慢慢理解在更新这篇博客。现在先死记硬背,记住就行。
2.先序遍历建立二叉树
void CreateBiTree(BiTree *t)
{
char ch;
scanf("%c",&ch);
if(ch=='@') *t=NULL;
else
{
*t=(BiTNode *)malloc(sizeof(BiTNode));
(*t)->data=ch;
CreateBiTree(&(*t)->lchild);
CreateBiTree(&(*t)->rchild);
}
}
这里的CreateBiTree(&(*t)->lchild);
,要记住用&(*t),地址的地址。慢慢理解,先记住。
3.后续遍历二叉树(递归算法)
void post_order_traverse(BiTree t)
{
if(t)
{
post_order_traverse(t->lchild);
post_order_traverse(t->rchild);
printf("%c",t->data);
}
}
4.中序遍历二叉树(递归算法)
void in_order_traverse(BiTree t)
{
if(t)
{
in_order_traverse(t->lchild);
printf("%c",t->data);
in_order_traverse(t->rchild);
}
}
非递归的算法我还没开始学,以后我会更新的!
遍历的形式参数要用BiTree t
,操作比较简单。记下来,只有建立二叉树形式参数需要用二级指针即BiTree *t
。
5.计算二叉树的深度
int Depth(BiTree t)
{
int ldepth=0,rdepth=0;
if(t==NULL) return 0;
else
{
ldepth=Depth(t->lchild);
rdepth=Depth(t->rchild);
if(ldepth>rdepth) return ldepth+1;
else return rdepth+1;
}
}
6.计算二叉树叶子节点个数
int LeafCount(BiTree *t)
{
if((*t)==NULL) return 0;
else
{
if((*t)->lchild==NULL&&(*t)->rchild==NULL) return 1;
else return LeafCount(&(*t)->lchild)+LeafCount(&(*t)->rchild);
}
}
可以用这种放法,也可以用BiTree t
。这种编写起来比较麻烦,可以参考下一编写方式。
7.计算孩子兄弟法的二叉树的叶子节点
int CSLeafCount(BiTree t)
{
if(t==NULL) return 0;
if(t->lchild==NULL) return 1+CSLeafCount(t->rchild);
else return CSLeafCount(t->rchild)+CSLeafCount(t->lchild);
}
当然,按照序号6函数操作,可以写为
int CSLeafCount(BiTree *t)
{
if((*t)==NULL) return 0;
if((*t)->lchild==NULL) return 1+CSLeafCount(&(*t)->rchild);
else return CSLeafCount(&(*t)->rchild)+CSLeafCount(&(*t)->lchild);
}
这个写起来麻烦。