在复习数据结构的过程中,二叉树一直都是重点也是难点,首先回顾了基础的二叉树递归遍历操作,二叉树的叶子结点个数以及二叉树的copy操作,以后会进阶二叉树的非递归遍历以及二叉树的创建过程。现在来看一下自己回顾基础写的代码,工作后业余时间有限,能够学习的时间和精力真是很宝贵,也纪念一下自己毕业快半年的节奏.
Just Like! Just Do IT:
#include "stdlib.h"
#include "stdio.h"
#include "string.h"
typedef struct BiTNode
{
int data;
struct BiTNode* lchild, *rchild;
}BiTNode, *BiTree;
int count = 0;
//先序遍历的访问
void PreOrder(BiTNode* bitnode)
{
if (bitnode != NULL)
{
printf("%d\t", bitnode->data);
PreOrder(bitnode->lchild);
PreOrder(bitnode->rchild);
}
}
//中序遍历
void InOrder(BiTNode* bitnode)
{
if (bitnode != NULL)
{
InOrder(bitnode->lchild);
printf("%d\t", bitnode->data);
InOrder(bitnode->rchild);
}
}
//后序遍历
void PostOrder(BiTNode* bitnode)
{
if (bitnode != NULL)
{
PostOrder(bitnode->lchild);
PostOrder(bitnode->rchild);
printf("%d\t", bitnode->data);
}
}
//求叶子节点的个数
void CountLeaf(BiTNode* bitnode)
{
//求叶子节点的个数就是遍历的过程
if (bitnode != NULL)
{
if (bitnode->lchild == NULL && bitnode->rchild == NULL)
{
count++;
}
CountLeaf(bitnode->lchild);
CountLeaf(bitnode->rchild);
}
}
//求叶子节点个数
void CountLeaf2(BiTNode* bitnode,int* count)
{
if (bitnode != NULL)
{
if (bitnode->lchild == NULL && bitnode->rchild == NULL)
{
(*count)++;
}
CountLeaf2(bitnode->lchild,count);
CountLeaf2(bitnode->rchild,count);
}
}
//二叉树的拷贝 遍历思想 先复制根节点 在复制左子树 和 右子树
BiTNode* CopyTree(BiTNode* bitnode)
{
BiTNode* newnode = NULL, *newlchild = NULL, *newrchild = NULL;
if (bitnode == NULL)
{
return NULL;
}
else
{
newnode = (BiTNode*)malloc(sizeof(BiTNode));
newnode->data = bitnode->data;
}
if (bitnode->lchild == NULL)
{
newlchild = NULL;
}
else
{
newlchild = CopyTree(bitnode->lchild);
}
if (bitnode->rchild == NULL)
{
newrchild = NULL;
}
else
{
newrchild = CopyTree(bitnode->rchild);
}
newnode->lchild = newlchild;
newnode->rchild = newrchild;
return newnode;
}
void TestDemo1()
{
int mycount = 0;
BiTNode b1, b2, b3, b4, b5,*newtree;
memset(&b1, 0, sizeof(BiTNode));
memset(&b2, 0, sizeof(BiTNode));
memset(&b3, 0, sizeof(BiTNode));
memset(&b4, 0, sizeof(BiTNode));
memset(&b5, 0, sizeof(BiTNode));
b1.data = 11;
b2.data = 22;
b3.data = 33;
b4.data = 44;
b5.data = 55;
b1.lchild = &b2;
b1.rchild = &b3;
b2.rchild = &b4;
b3.lchild = &b5;
printf("先序遍历:");
PreOrder(&b1);
printf("\n中序遍历:");
InOrder(&b1);
printf("\n后续遍历:");
PostOrder(&b1);
CountLeaf(&b1);
printf("\n叶子节点个数:%d", count);
CountLeaf2(&b1, &mycount);
printf("\n叶子节点个数:%d", mycount);
newtree = CopyTree(&b1);
printf("\n拷贝二叉树中序遍历:");
InOrder(newtree);
}
void main()
{
TestDemo1();
printf("\n邵忠棋");
system("pause");
}