因为太懒了就直接上代码吧
遍历方法包含前、中、后序遍历以及层次遍历。
#include<iostream>
#include<queue>
using namespace std;
typedef struct Btree {
int val;
struct Btree* lchild;
struct Btree* rchild;
Btree():val(0),lchild(nullptr),rchild(nullptr){}
}node;
int luo_time = 1;
node* root = new node();
node* FindVal(const int& x,node* q) {//找出val值为x的节点,返回其地址
if (q->val == x&&q->lchild==nullptr&&q->rchild==nullptr) {
return q;
}
if (q->lchild != nullptr) {
node* w = FindVal(x, q->lchild);
if (w != nullptr) {
return w;
}
}
if (q->rchild != nullptr) {
node* w = FindVal(x, q->rchild);
//return w;
if (w != nullptr) {
return w;
}
}
return nullptr;
}
void AddNode(int par, int lch, int rch) {//为val值为par的节点添加左右孩子节点
Btree* f = FindVal(par, root);
if (f == nullptr) {
cout << "此次插入不成功!!!" << endl;
}
else {
node* temp1 = new node();
node* temp2 = new node();
temp1->val = lch, temp2->val = rch;
f->lchild = temp1, f->rchild = temp2;
}
}
void PrintLevel(node* m) {//层次遍历
cout << "层次遍历:" << endl;
queue<node*>p;
p.push(m);
while (!p.empty()) {
node* x = p.front();
cout << x->val << " ";
p.pop();
if (x->lchild != nullptr) {
p.push(x->lchild);
}
if (x->rchild != nullptr) {
p.push(x->rchild);
}
}
}
void PrintBtreeq(node* m) {//前序遍历二叉树
if (m != nullptr) {
cout << m->val << " ";
if (m->lchild != nullptr) {
PrintBtreeq(m->lchild);
}
if (m->rchild != nullptr) {
PrintBtreeq(m->rchild);
}
}
else {
return;
}
}
void PrintBtreez(node* m) {//中序遍历
if (m != nullptr) {
if (m->lchild != nullptr) {
PrintBtreez(m->lchild);
}
cout << m->val << " ";
if (m->rchild != nullptr) {
PrintBtreez(m->rchild);
}
}
}
void PrintBtreeh(node* m) {//后序遍历
if (m != nullptr) {
if (m->lchild != nullptr) {
PrintBtreeh(m->lchild);
}
if (m->rchild != nullptr) {
PrintBtreeh(m->rchild);
}
cout << m->val << " ";
}
}
void CreatBtree() {//创建二叉树
int par, lch, rch;
cout << "输入二叉树的节点:(范例:1 2 3,这是以1为父亲节点,2和3分别为1的左右孩子节点)" << endl;
cout << "当我们输入0 0 0时即代表停止输入!" << endl;
cin >> par >> lch >> rch;
while (par != 0 || lch != 0 || rch != 0) {
if (luo_time == 1) {
root->val = par;
node* tmp1 = new node();
node* tmp2 = new node();
//f->lchild = new Btree(), f->rchild = new Btree();
tmp1->val = lch, tmp2->val = rch;
root->lchild = tmp1, root->rchild = tmp2;
}
else {
AddNode(par, lch, rch);
}
//cout << "输出测试:" << endl;
//PrintBtreeh(root);
//cout << endl;
luo_time++;
cin >> par >> lch >> rch;
}
}
int main() {
CreatBtree();
PrintLevel(root);
cout << "\n" << "前序遍历:" << endl;
PrintBtreeq(root);
cout << "\n" << "中序遍历:" << endl;
PrintBtreez(root);
cout << "\n" << "后序遍历:" << endl;
PrintBtreeh(root);
return 0;
}