前序遍历
void PrevOrder(BTNode* root)
{
if (root == NULL)
{
printf("NULL ");
return;
}
printf("%c ", root->x);
PrevOrder(root->left);
PrevOrder(root->right);
}
中序遍历
void InOrder(BTNode* root)
{
if (root == NULL)
{
printf("NULL ");
return;
}
InOrder(root->left);
printf("%c ", root->x);
InOrder(root->right);
}
后序遍历
void PostOrder(BTNode* root)
{
if (root == NULL)
{
printf("NULL ");
return;
}
PostOrder(root->left);
PostOrder(root->right);
printf("%c ", root->x);
}
层序遍历
void TreeLevelOrder(BTNode* root)
{
Queue q;
QueueInit(&q);
if (root != NULL)
QueuePush(&q, root);
while (!QueueEmpty(&q))
{
BTNode* front = QueueFront(&q);
QueuePop(&q);
printf("%c ", front->x);
if (front->left != NULL)
{
QueuePush(&q, front->left);
}
if (front->right != NULL)
{
QueuePush(&q, front->right);
}
}
QueueDestroy(&q);
}
二叉树第k层的结点个数
int TreeKLevelSize(BTNode* root, BTData k)
{
if (root == NULL)
return 0;
if (k == 1)
return 1;
return TreeKLevelSize(root->left, k - 1) + TreeKLevelSize(root->right, k - 1);
}
一棵树的结点总个数
int TreeSize2(BTNode* root)
{
return root == NULL ? 0 : (TreeSize2(root->left) + TreeSize2(root->right) + 1);
}
在树中查找值为x的结点
BTNode* TreeFind(BTNode* root, BTData x)
{
BTNode* leftRet = NULL;
BTNode* rightRet = NULL;
if (root == NULL)
return NULL;
if (root->x == x)
return root;
leftRet = TreeFind(root->left, x);
if (leftRet != NULL)
return leftRet;
rightRet = TreeFind(root->right, x);
if (rightRet != NULL)
return rightRet;
return NULL;
}