#include<iostream>
using namespace std;
class Tree {
char data;
Tree *Leftchild;
Tree *Rightchild;
public:
Tree()//创建二叉树
{
data = '#';
}
void CreatTree()
{
char a;
cin >> a;
if (a == '#')
{
Leftchild = NULL;
Rightchild = NULL;
return;
}
data = a;
Leftchild = new Tree;
Leftchild->CreatTree();
Rightchild = new Tree;
Rightchild->CreatTree();
}
void PreTree()//前序遍历 根左右
{
if (this->data == '#')
{
return;
}
cout << this->data << " ";
this->Leftchild->PreTree();
this->Rightchild->PreTree();
}
void InTree()//中序遍历 左 右 根
{
if (this->data == '#')
return;
Leftchild->InTree();
cout << this->data<<" ";
Rightchild->InTree();
}
void PostTree()//后序遍历 左右根
{
if (this->data == '#')
{
return;
}
this->Leftchild->PostTree();
this->Rightchild->PostTree();
if (this->data)
cout << this->data << " ";
}
};
int main()
{
Tree *t = new Tree;
t->CreatTree();
cout << "前序遍历:";
t->PreTree();
cout << endl;
cout << "中序遍历:";
t->InTree();
cout << endl;
cout << "后序遍历:";
t->PostTree();
system("pause");
return 0;
}
层次遍历
``void LevelTree(Tree* T)//层次遍历
{
queue<Tree*> q;
Tree* t;
if (!T)
return;
q.push(T);
while (!q.empty())
{
t = q.front();
q.pop();
cout << t->data << " ";
if (t->Leftchild)
q.push(t->Leftchild);
if (t->Rightchild)
q.push(t->Rightchild);
}
}
求树的高度 递归法
```cpp
int GetHeight(BinTree BT){
int hl,hr,maxh;
if(BT){
hl = GetHeight(BT->Left); // 求左子树高度
hr = GetHeight(BT->Right); // 求右子树高度
maxh = (hl>hr)?hl:hr;
return maxh+1; // 当前结点高度为左右子树最大的高度+1
}else
return 0;
}
二叉树前序、中序、后序遍历递归实现——c++
最新推荐文章于 2023-01-25 14:51:23 发布
本文详细介绍了如何使用C++编程语言,通过递归方式实现二叉树的前序、中序和后序遍历。通过具体代码示例,帮助读者理解不同遍历顺序的逻辑和实现细节。
摘要由CSDN通过智能技术生成