前言:遍历是数据结构中的一种基本且重要的算法,许多算法都是基于遍历之上实现的。相对于线性表,树是一种非线性结构,不能单纯地利用循环思想进行遍历,而是递归的思想,因为树是一种递归的数据结构(树的定义是递归的)。
以下对二叉树的递归遍历算法以及基于递归遍历实现的其他算法进行总结。
实现的算法有:
二叉树的遍历分为:
前、中、后序遍历,对应的遍历过程为:根左右、左根右、左右根。
实际上什么序遍历是根据访问根结点访问顺序而得,而前序遍历也可以以“根右左”的顺序遍历,但实际上默认使用“先左后右”的顺序。
很重要的:
回顾二叉树的定义(二叉树递归算法的核心思想):
一个有限的结点集合:这个集合或者为空;或者由一个根结点以及两个称为左子树和右子树的互不相交的二叉树的结点集合组成。
实现代码:
类型声明:
typedef struct node
{
ElemType data;
struct node *lchild;
struct node *rchild;
}BTNode;
//一个递归模型由两部分组成:
//1. 递归出口:递归结束条件 + 执行语句
//2. 递归体:递归体执行条件 + 递归语句
void PreTravel (BTNode *btree_p)
{
if (btree_p == NULL)
return ;
else
{
printf("%c", btree_p->data);
PreTravel(btree_p->lchild);
PreTravel(btree_p->rchild);
}
}
bool Like(BTNode *btree_p1, BTNode btree_p2)
{
if (btree_p1 == NULL && btree_p2 == NULL)
return true;
else if (btree_p1 == NULL || btree_p2 == NULL)
return false;
else
{
bool like1 = Like(btree_p1->lchild, btree_p2->lchild);
bool like2 = Like(btree_p2->rchild, btree_p2->rchild);
return like1 && like2;
}
}
void PrintLeaf (BTNode *btree_p)
{
if (btree_p == NULL)
return ;
else if (btree_p->lchild == NULL && btree_p->rchild == NULL)
printf("%c", btree_p->data);
else
{
PrintLeaf(btree_p->lchild);
PrintLeaf(btree_p->rchild);
}
}
int NodesCount(BTNode *btree_p)
{
if (btree_p == NULL)
return 0;
else
return (NodesCount(btree_p->lchild) + NodesCount(btree_p-rchild) + 1);
}
//调用格式:NodesLevel(btree_p, 1, find_data);
//height形参用字面值1初始化
int NodeLevel(BTNode *btree_p, int height, ElemType find_data)
{
if (btree_p == NULL)
return 0;
else if (btree_p->data == find_data)
return height;
else
{
height2 = NodeLevel(btree_p->lchild, height+1, find_data);
if (height2 != 0)
return height2;
else
return (NodeLevel(btree_p->rchild, height+1, find_data));
}
}
void LevelNodesCount(BTNode *btree_p, int height_now, int height_goal, int &count)
{
if (btree_p == NULL)
return ;
else if (height_now == height_goal)
count++;
else if (height_now < height_goal)
{
LevelNodesCount(btree_p->lchild, height_now+1, height_goal, count);
LevelNodesCount(btree_p->rchild, height_now+1, height_goal, count);
}
}
bool Ancestor(BTNode *btree_p, ElemType find_data)
{
if (btree_p == NULL)
return false;
else if (btree_p->lchild != NULL && btree_p->lchild->data == find_data || btree_p->rchild != NULL && btree_p->rchild->data == find_data)
{
printf("%c", btree_p->data);
return true;
}
else if (Ancestor(btree_p->lchild, find_data) || Ancestor(btree_p->rchild, find_data))
{
printf("%c", btree_p->data);
return true;
}
else
return flase;
}