- 本周的学习内容包括:
1.树与二叉树
a、树与二叉树的基本概念
b、二叉树的前序、中序、后序遍历(递归与非递归)
2.二叉查找树
a、二叉查找树的基本概念
b、二叉查找树的建立与查找
c、二叉查找树节点删除
d、使用二叉查找树进行排序
e、例题:二叉查找树编码与解码
正文
今日学习:树与二叉树的基本概念、二叉树的前序、中序、后序遍历(递归与非递归)
1、树与二叉树基本概念
2、二叉树的遍历
所谓遍历如何定义:
- 二叉树的遍历之前序遍历
具体示意图:
代码:
- 二叉树的遍历之中序遍历
具体示意图:
代码:
- 二叉树的遍历之后序遍历
具体示意图:
代码:
- 二叉树的遍历-代码测试
#include<stdio.h>
#include<malloc.h>
#include<string.h>
struct Binary_Tree
{
int data;
struct Binary_Tree* left;
struct Binary_Tree* right;
};
void first_order(struct Binary_Tree* node)
{
if (node == NULL)
{
return;
}
printf("%d ", node->data);//父
first_order(node->left);//左节点
first_order(node->right);//右节点
}
void middle_order(struct Binary_Tree* node)
{
if (node == NULL)
{
return;
}
middle_order(node->left);//左节点
printf("%d ", node->data);//父
middle_order(node->right);//右节点
}//中序遍历
void back_order(struct Binary_Tree* node)
{
if (node == NULL)
{
return;
}
back_order(node->left);//左节点
back_order(node->right);//右节点
printf("%d ", node->data);//父
}//后序遍历
struct Binary_Tree* node_init(int val)
{
struct Binary_Tree* node = (struct Binary_Tree*)malloc(sizeof(struct Binary_Tree));//动态分配空间
node->data = val;
node->left = NULL;
node->right = NULL;
return node;
}//二叉树节点初始化
int main()
{
struct Binary_Tree* root = node_init(1);//根节点赋值为1
root->left = node_init(2);//2
root->right = node_init(3);//3
root->left->left = node_init(4);//4
root->left->right = node_init(5);//5
root->right->right = node_init(6);//6
printf("First order:\n");
first_order(root);//二叉树的遍历-前序遍历
printf("\nMiddle order:\n");
middle_order(root);//二叉树的遍历-中序遍历
printf("\nBack order:\n");
back_order(root);//二叉树的遍历-后序遍历
printf("\n");
return 0;
}
结果:
中场休息
其实上面的回溯遍历还是挺好玩的,会疑惑为什么会往上找呢?真心奇怪哦。而且我step by step 也没有看出为啥呢,真心奇怪。
其实就是一个递归,下面这个链接讲的很明白,而且还结合着几种类型的题目(1.根据前序遍历、中序遍历,求后序遍历;2已知中序和后序遍历,求前序遍历)来讲的,很值得看看。https://blog.csdn.net/android_cmos/article/details/52887028
该步递归的过程可以简洁表达如下:
1 确定根,确定左子树,确定右子树。
2 在左子树中递归。
3 在右子树中递归。
4 打印当前根。
3、二叉树的非递归遍历-前序遍历
二叉树的遍历,可以用第二课中的栈数据结构进行遍历,代替递归分方法
- 前序遍历
a、将根节点压入栈中
b、遍历栈顶节点后出栈,且将其右子节点,左子节点依此压入栈中
示意图:
代码:
哎!出错了。。