点击链接返回标题->基于非链式(数组)结点结构的二叉树的层序、先序、中序、后序输入创建以及层序、先序、中序、后序输出-CSDN博客
我们采用递归的思想,不断去找空结点(值为-1的结点),在找空结点这个过程中,将输入的x的值(即有效结点)“顺路”插入树中,直到发现输入的值是-1,也就是来到了空结点的位置,延递归路线返回即可,并遵循“先递归左子树,再递归右子树”的顺序,也就是先序的根左右。
- #include<iostream>
- using namespace std;
- typedef int datatype;
- const int MAX = 8;
- struct binTree {
- datatype tree[2 * MAX + 7];//该数组的最大容量必须超过最大结点数的两倍,用以存放空结点!
- int size;//当前有效结点个数
- };
-
- void create_tree_pre(binTree* tree, int i = 1) {//按先序创建二叉树
- int x;
- cin >> x;
- if (x != -1) {
- tree->tree[i] = x;
- tree->size++;
- }
- else return;//如果当前插入结点是-1的话,显然当前递归路线该返回了
- create_tree_pre(tree, i * 2);
- create_tree_pre(tree, i * 2 + 1);
- }
-
- void travse_pre(binTree* tree, int i = 1) {//二叉树的先序遍历
- if (tree->tree[i] == -1) return;//访问到空结点,该递归路线需要返回
- //根,左,右
- printf("%d ", tree->tree[i]);
- travse_pre(tree, i * 2);
- travse_pre(tree, i * 2 + 1);
- }
完整测试代码如下:
样例输入:
1 2 4 -1 -1 5 -1 -1 3 6 -1 -1 7 -1 -1
样例输出:
层序遍历结果——1 2 3 4 5 6 7
先序遍历结果——1 2 4 5 3 6 7
中序遍历结果——4 2 5 1 6 3 7
后序遍历结果——4 5 2 6 7 3 1
- #include<iostream>
- using namespace std;
- typedef int datatype;
- const int MAX = 8;
- struct binTree {
- datatype tree[2 * MAX + 7];//该数组的最大容量必须超过最大结点数的两倍,用以存放空结点!
- int size;//当前有效结点个数
- };
-
- void create_tree_pre(binTree* tree, int i = 1) {//按先序创建二叉树
- int x;
- cin >> x;
- if (x != -1) {
- tree->tree[i] = x;
- tree->size++;
- }
- else return;//如果当前插入结点是-1的话,显然当前递归路线该返回了
- create_tree_pre(tree, i * 2);
- create_tree_pre(tree, i * 2 + 1);
- }
-
-
- void travse_seq(binTree* tree) {//二叉树的层序遍历
- int len = tree->size, i = 1;
- while (len) {
- if (tree->tree[i] != -1) {//访问到的不是空结点就输出,并让len自减,len为0时所有有效结点均被输出
- printf("%d ", tree->tree[i++]);
- len--;
- }
- }
- }
- void travse_pre(binTree* tree, int i = 1) {//二叉树的先序遍历
- if (tree->tree[i] == -1) return;//访问到空结点,该递归路线需要返回
- //根,左,右
- printf("%d ", tree->tree[i]);
- travse_pre(tree, i * 2);
- travse_pre(tree, i * 2 + 1);
- }
- void travse_mid(binTree* tree, int i = 1) {//二叉树的中序遍历
- if (tree->tree[i] == -1) return;
- //左,根,右
- travse_mid(tree, i * 2);
- printf("%d ", tree->tree[i]);
- travse_mid(tree, i * 2 + 1);
- }
- void travse_nex(binTree* tree, int i = 1) {//二叉树的后序遍历
- if (tree->tree[i] == -1) return;
- //左,右,根
- travse_nex(tree, i * 2);
- travse_nex(tree, i * 2 + 1);
- printf("%d ", tree->tree[i]);
- }
- void test(binTree* tree) {
- create_tree_pre(tree);
-
- cout << "层序遍历结果——";
- travse_seq(tree);
- cout << endl;
-
- cout << "先序遍历结果——";
- travse_pre(tree);
- cout << endl;
-
- cout << "中序遍历结果——";
- travse_mid(tree);
- cout << endl;
-
- cout << "后序遍历结果——";
- travse_nex(tree);
- cout << endl;
- }
- int main() {
- binTree tree;
- tree.size = 0;
- memset(tree.tree, -1, sizeof(tree.tree));//初始化树的相关信息
- test(&tree);
- }