二叉树的构建及其前中后序遍历(c++)
我们要解决的问题:
给定一个长度为len的int类型数组,构造一棵二叉树,并输出这棵树的前中后序遍历。
二叉树由一个个的节点构成,每个节点包含三个东西,分别是这个节点的数据,这个节点的左儿子的地址和右儿子的地址,所以这里使用结构体来表示一个节点。
所以,先写二叉树节点的代码
struct Binary_node
{
int data;
Binary_node *left;
Binary_node *right;
Binary_node(
int x):left(
0),right(
0){data = x}
};
然后写一个二叉树的类的声明
class Binary_tree
{
private:
Binary_node *root;
public:
Binary_tree();
Binary_tree(
int *arr,
int len);
void pre_order(
const Binary_node *p);
void pre_print();
void in_order(
const Binary_node *p);
void in_print();
void post_order(
const Binary_node *p);
void post_print();
};
·数据结构的一个规定:能够在main程序里面被调用的一般叫做【方法】,其他的叫做【函数】。
接下来写Binary__tree类里面的函数和方法的实现
Binary_tree::Binary_tree()
{
root =
NULL;
}
Binary_tree::Binary_tree(
int *arr,
int len)
{
root =
NULL;
int index =
0;
while (len--){
if (root ==
NULL){
root = new Binary_node(arr[index++]);
continue;
}
Binary_node *p = root;
int tmp = arr[index++];
while (p->data!=tmp){
if (tmp > p->data){
if (p->right !=
NULL) p = p->right;
else
{
p->right = new Binary_node(tmp);
break;
}
}
else{
if (p->left !=
NULL) p = p->left;
else
{
p->left = new Binary_node(tmp);
break;
}
}
}
}
}
void Binary_tree::pre_order(
const Binary_node *p)
{
if (p ==
NULL)
return;
cout << p->data <<
' ';
pre_order(p->left);
pre_order(p->right);
}
void Binary_tree::pre_print()
{
pre_order(root);
cout << endl;
}
void Binary_tree::in_order(
const Binary_node *p)
{
if (p ==
NULL)
return;
in_order(p->left);
cout << p->data <<
' ';
in_order(p->right);
}
void Binary_tree::post_order(
const Binary_node *p)
{
if (p ==
NULL)
return;
post_order(p->left);
post_order(p->right);
cout << p->data <<
' ';
}
·【访问】的意思指的是打印出这个节点的数值
最后写一下main函数
#include <iostream>
#include "头文件.h"
using namespace std;
int main()
{
int num;
cin >> num ;
int *arr =
new int[num] ;
for(
int i =
0; i < num; i++)
cin >> arr[i];
Binary_tree apple_tree(arr,num);
apple_tree.pre_print();
return 0;
}
·*请仔细阅读代码的注释,我所有的想法都写在注释里面了。
欢迎交流,欢迎评论。