(1)二叉树的创建
(2)二叉树的销毁
(3)二叉树的遍历(先序遍历、中序遍历、后序遍历和层次遍历)//包含中、先序的非递归
(4)用括号表示法输出二叉树
代码示例
#include <stdio.h>
#include <stdlib.h>
typedef struct TreeNode
{
char data;
struct TreeNode *left;
struct TreeNode *right;
}bitree;
struct TreeNode *createNode(char data)
{
struct TreeNode *newNode = (struct TreeNode *)malloc(sizeof(struct TreeNode));
if (newNode == NULL)
{
printf("内存分配失败\n");
exit(EXIT_FAILURE);
}
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
void destroyTree(struct TreeNode *root)
{
if (root == NULL)
{
return;
}
destroyTree(root->left);
destroyTree(root->right);
free(root);
}
void preorderTraversal(struct TreeNode *root)
{
if (root == NULL)
{
return;
}
printf("%c ", root->data);
preorderTraversal(root->left);
preorderTraversal(root->right);
}
void inorderTraversal(struct TreeNode *root)
{
if (root == NULL)
{
return;
}
inorderTraversal(root->left);
printf("%c ", root->data);
inorderTraversal(root->right);
}
void postorderTraversal(struct TreeNode *root)
{
if (root == NULL)
{
return;
}
postorderTraversal(root->left);
postorderTraversal(root->right);
printf("%c ", root->data);
}
void levelOrderTraversal(struct TreeNode *root)
{
if (root == NULL)
{
return;
}
struct TreeNode *queue[100];
int front = 0, rear = 0;
queue[rear++] = root;
while (front < rear)
{
struct TreeNode *current = queue[front++];
printf("%c ", current->data);
if (current->left != NULL)
{
queue[rear++] = current->left;
}
if (current->right != NULL)
{
queue[rear++] = current->right;
}
}
}
void printParenthetical(struct TreeNode *root)
{
if (root == NULL)
{
return;
}
printf("%c", root->data);
if (root->left != NULL || root->right != NULL)
{
printf("(");
printParenthetical(root->left);
printf(",");
printParenthetical(root->right);
printf(")");
}
}
int main()
{
struct TreeNode *root = createNode('A');
root->left = createNode('B');
root->right = createNode('C');
root->left->left = createNode('D');
root->left->right = createNode('E');
printf("先序遍历: ");
preorderTraversal(root);
printf("\n");
printf("中序遍历: ");
inorderTraversal(root);
printf("\n");
printf("后序遍历: ");
postorderTraversal(root);
printf("\n");
printf("层次遍历: ");
levelOrderTraversal(root);
printf("\n");
printf("括号表示法: ");
printParenthetical(root);
printf("\n");
destroyTree(root);
return 0;
}