二叉树遍历的本质:
先序中序后序遍历:每个结点都要被“访问”3次,只是访问的时机不同。
typedef struct BiTNode //二叉链表
{
int data;
struct BiTNode *lchild, *rchild; //左孩子 右孩子
}BiTNode, *BiTree;
void PreOrder(BiTNode* T)//先序遍历二叉树
{
if(T!=NULL)
{
printf("%d\n",T->data);
PreOrder(T->lchild);
PreOrder(T->rchild);
}
}
遍历是绝大多数二叉树操作的前提
//求总结点个数
//访问结点,结点不为空,则g_count++
int count = 0;
void CountLeaf(BiTree T) //二叉树总结点数目
{
if(T != NULL)
{
count++;
count_1(T->lchild);
count_1(T->rchild);
}
}
-----------------------------------------------------------------------
//求叶子结点总个数
//访问结点,结点不为空的前提下,再判断该结点是否为叶子,如果是,g_count++
int g_count = 0;
void CountLeaf(BiTNode *T) //二叉树叶子结点总数目
{
if (T != NULL)
{
CountLeaf(T->lchild);
CountLeaf(T->rchild);
if (T->lchild == NULL && T->rchild == NULL)
{
g_count ++;
}
}
}
----------------------------------------------------------------------
//求二叉树的深度
int Depth(BiTNode* T)
{
int depth_L = 0,depth_R = 0;
if(T == NULL) //如果树根T是空
return 0;
else
{
depth_L = 1+Depth(T->lchild); //1+左子树的树深
depth_R = 1+Depth(T->rchild); //1+右子树的树深
return depth_L>depth_R?depth_L:depth_R;
}
}
/* 二叉树复制 */
BiTNode* copyBiTree(BiTNode* T)
{
if(T == NULL)
return NULL;
else
{
BiTNode* pNew= (BiTNode*)malloc(sizeof(BiTNode));
pNew->data = T->data;
pNew->lchild = copyBiTree(T->lchild);
pNew->rchild = copyBiTree(T->rchild);
return pNew;
}
}
-------------------------------------------------------
//二叉树的创建(先序+字符串AB#D##CE#F### )
BiTNode* create_Tree()
{
char ch;
scanf("%c",&ch);
if(ch == '#')
return NULL;
else
{
BiTNode *pNew = new BiTNode;
pNew->data = ch;
pNew->lchild = create_Tree();
pNew->rchild = create_Tree();
return pNew;
}
}
//输入: AB#D##CE#F###
//先序遍历结果:ABDCEF
遗留问题:
二叉树的插入
二叉树的创建
二叉树的删除
二叉树的查找
线索二叉树
先序中序后序层序--->非递归遍历二叉树