
勤时当勉励 岁月不待人
C/C++ 游戏开发
Hello,米娜桑们,这里是君兮_,有了我们之前介绍的树结构与二叉树的基础概念,今天我们来讲讲对二叉树的基本使用——遍历
typedef struct BinaryTreeNode
{
struct BinaryTreeNode* left;
struct BinaryTreeNode* right;
int val;
}BTNode;
//初始化
BTNode* BuyNode(int x)
{
BTNode* node = (BTNode*)malloc(sizeof(BTNode));
if (node == NULL)
{
perror("malloc fail");
exit(-1);
}
node->val = x;
node->left = node->right = NULL;
return node;
}
int main()
{
//手动构建
BTNode* node1 = BuyNode(1);
BTNode* node2 = BuyNode(2);
BTNode* node3 = BuyNode(3);
BTNode* node4 = BuyNode(4);
BTNode* node5 = BuyNode(5);
BTNode* node6 = BuyNode(6);
node1->left = node2;
node1->right = node4;
node2->left = node3;
node4->left = node5;
node4->right = node6;
int size = TreeLeafSize(node1);
printf("%d", size);
return 0;
}
void PrevOrder(BTNode* root)
{
if (root == NULL)
return;
printf("%d ", root->val);
PrevOrder(root->left);
PrevOrder(root->right);
}
if (root == NULL)
return;
printf("%d ", root->val);
PrevOrder(root->left);
PrevOrder(root->right);




void InOrder(BTNode* root)
{
if (root == NULL)
return;
InOrder(root->left);
printf("%d ", root->val);
InOrder(root->right);
}




void PostOrder(BTNode* root)
{
if (root == NULL)
return;
PostOrder(root->left);
PostOrder(root->right);
printf("%d ", root->val);
}



void LevelOrder(BTNode* root)
{
Que q;
QueueInit(&q);//初始化队列
if (root)
QueuePush(&q, root);//把要遍历的二叉树的根节点插入队列中
while (!QueueEmpty(&q))//队列判空
{
BTNode* front = QueueFront(&q);//获取队首元素
printf("%d ", front->val);//打印队首存储的元素
if (front->left)//队首的左子树不为空就把左子树插入队列
QueuePush(&q, front->left);
if (front->right)//队首的右子树不为空就把右子树插入队列
QueuePush(&q, front->right);
QueuePop(&q);//让队首离队
}
printf("\n");
QueueDestroy(&q);//销毁队列
}






新人博主创作不易,如果感觉文章内容对你有所帮助的话不妨三连一下再走呗。你们的支持就是我更新的动力!!!
**(可莉请求你们三连支持一下博主!!!点击下方评论点赞收藏帮帮可莉吧)**
