二叉树前序、中序、后序遍历递归实现——c++

本文详细介绍了如何使用C++编程语言,通过递归方式实现二叉树的前序、中序和后序遍历。通过具体代码示例,帮助读者理解不同遍历顺序的逻辑和实现细节。
摘要由CSDN通过智能技术生成
#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;
} 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值