二叉树的结点表示
左子树,右子树,结点数据
typedef struct TNode *Position;
typedef Position BinTree; /* 二叉树类型 */
struct TNode{
/* 树结点定义 */
ElementType Data; /* 结点数据 */
BinTree Left; /* 指向左子树 */
BinTree Right; /* 指向右子树 */
};
二叉树的遍历(递归)
printf根节点的数据;
中序遍历,左子树->根节点->右子树;
void InorderTraversal( BinTree BT )
{
if( BT ) {
InorderTraversal( BT->Left );
/* 此处假设对BT结点的访问就是打印数据 */
printf("%d ", BT->Data); /* 假设数据为整型 */
InorderTraversal( BT->Right );
}
}
前序遍历,根节点->左子树->右子树;
void PreorderTraversal( BinTree BT )
{
if( BT ) {
printf("%d ", BT->Data );
PreorderTraversal( BT->Left );
PreorderTraversal( BT->Right );
}
}
后序遍历,左子树->右子树->根节点;
void PostorderTraversal( BinTree BT )
{
if( BT ) {
PostorderTraversal( BT->Left );
PostorderTraversal( BT->Right );
printf("%d ", BT->Data);
}
}
层序遍历——类似BFS
创建队列,从根节点开始入队,子树从左至右入队;
结点出队后输出,并且左右子树顺序入队,即可完成层序遍历;
void LevelorderTraversal ( BinTree BT )
{
Queue Q;
BinTree T;
if ( !BT ) return; /* 若是空树则直接返回 */
Q = CreatQueue(); /* 创建空队列Q */
AddQ( Q, BT );
while ( !IsEmpty(Q) ) {
T = DeleteQ( Q );
printf("%d ", T->Data)