二叉树的层序遍历,用堆栈先序遍历,递归树的深度

队列实现层序遍历,以及改为堆栈先序遍历

#include<iostream>
using namespace std;
typedef int ElemType;
typedef struct BinTree
{
	ElemType data;
	struct BinTree* Left;
	struct BinTree* Right;
}BinTree;
typedef struct Queue
{
	ElemType data;
	struct Queue* Frond;
	struct Queue* rear;
}Queue;
void LevelOrderTraversal(BinTree* BT)//层序遍历,用队列
{
	Queue* Q;
	BinTree* T;
	if(!BT)return ;
	Q=CreatQueue(MaxSize);//创建并初始化队列
	AddQ(Q,BT);
	while(!IsEmpty(Q))
	{
		T=Delete(Q);
		cout<<T->data<<" ";
		if(T->Left) Add(Q,T->Left);//加入队列
		if(T->Right) Add(Q,T->Right);
	}
}
//可以用堆栈来实现二叉树的先序遍历
//即对调左右子树的加入顺序先Add(Q,T->Right),后Add(Q,T->Left),再;

递归树的深度

#include<iostream>
#include<algorithm>
using namespace std;
typedef int ElemType;
typedef struct BinTree
{
	ElemType data;
	struct BinTree* Left;
	struct BinTree* Right;
}BinTree;
int PostOrderGetHeight(BinTree* BT)//递归二叉树深度
{
	int HL,HR,MaxH;
	if(BT)
	{
		HL=PostOrderGetHeight(BT->Left);
		HR=PostOrderGetHeight(BT->Right);
		MaxH=max(HR,HL);
		return MaxH+1;
	}
	else return 0;
}
posted @ 2022-01-28 22:40  帝宝单推人!  阅读(79)  评论(0)    收藏  举报