1.二叉树的结构
typedef int BTDataType;
typedef struct BinaryTreeNode
{
BTDataType val;
struct BinaryTreeNode* left;
struct BinaryTreeNode* right;
}BTNode;
就比如如下结构:
2.前序遍历
手搓一棵树
BTNode* CreateTree2()
{
BTNode* n1 = BuyNode(1);
BTNode* n2 = BuyNode(2);
BTNode* n3 = BuyNode(3);
BTNode* n4 = BuyNode(4);
BTNode* n5 = BuyNode(5);
BTNode* n6 = BuyNode(6);
n1->left = n2;
n1->right = n4;
n2->left = n3;
n4->left = n5;
n4->right = n6;
return n1;
}
代码实现:
void PreOrder(BTNode* root)
{
if (root == NULL)
{
printf("N ");
return;
}
printf("%d ", root->val);
PreOrder(root->left);
PreOrder(root->right);
}
3.中序遍历
代码实现:
void InOrder(BTNode* root)
{
if (root == NULL)
{
printf("N ");
return;
}
InOrder(root->left);
printf("%d ", root->val);
InOrder(root->right);
}
4.后序遍历
代码实现:
void PostOrder(BTNode* root)
{
if (root == NULL)
{
printf("N ");
return;
}
PostOrder(root->left);
PostOrder(root->right);
printf("%d ", root->val);
}
5.层序遍历
层序遍历,顾名思义,就是一层一层遍历。这里就不用递归了,需要用到队列。
采取的思想是父亲带孩子的思想。
我们这里要用到队列,所以要有队列的程序。怎么把原先写好的代码放到二叉树的程序里呢?
按照以下顺序:
第一步:右击源文件,在添加里找到现有项,点击。
第二步:在所在文件夹里找到队列的文件夹
第三步:选中所要用到的,复制
第四步:回到原来的文件夹里,粘贴以上两个 Queue.c和Queue.h
第五步:将Queue.h移到头文件里,直接拖动就好
代码实现:
void LevelOrder(BTNode* root)
{
Que q;
QueueInit(&q);
if (root)
{
QueuePush(&q, root);
}
while (!QueueEmpty(&q))
{
BTNode* front = QueueFront(&q);
QueuePop(&q);
printf("%d ", front->val);
if (front->left)
{
QueuePush(&q, front->left);
}
if (front->right)
{
QueuePush(&q, front->right);
}
}
QueueDestory(&q);
}
over~