数据结构 | 层次遍历&求二叉树的高度(递归&非递归)

层次遍历

#include
#include
using namespace std;
struct BTNode
{
	int data;
	BTNode* left, * right;
	BTNode(int val) :data(val), left(NULL), right(NULL) {}

};
static void LevelSort(BTNode* t)
{
	if (t == NULL)
		return;
	queue q;
	q.push(t);
	while (!q.empty())
	{
		t = q.front();
		q.pop();
		cout << t->data<<'\t';
		if (t->left) q.push(t->left);
		if (t->right) q.push(t->right);
	}
}
int main()
{
	BTNode* root = new BTNode(1);
	root->left = new BTNode(2);
	root->right = new BTNode(3);
	root->left->left = new BTNode(4);
	root->left->right = new BTNode(5);
	root->right->left = new BTNode(6);
	root->right->right = new BTNode(7);
	cout << "层次遍历:" << endl;
	LevelSort(root);
	return 0;
}

 

求高度

#include
#include
using namespace std;
struct BTNode
{
	int data;
	BTNode* left, * right;
	BTNode(int val) :data(val), left(NULL), right(NULL) {}

};
//求高度递归
/*int GetHeight(BTNode* t)
{
	if (t == NULL)
		return 0;
	int l = GetHeight(t->left);
	int r = GetHeight(t->right);
	return 1 + (l > r ? l : r);
}*/
//求高度 非递归
 int GetHeight(BTNode* t)
{
	if (t == NULL)
		return 0;
	int level = 0;
	queue q;
	q.push(t);
	while (!q.empty())
	{ 
		int n = q.size();  //计算当前结点的个数
		for (int i = 0; i < n; i++) //以当前结点个数为循环次数 当循环结束 当前结点全部pop出去 他们的孩子留下来 
		{
			t = q.front(); //t 为队列第一个元素
			q.pop();
			if (t->left) q.push(t->left);
			if (t->right) q.push(t->right);

		}
		level++;
	}
	return level;


}
int main()
{
	BTNode* root = new BTNode(1);
	root->left = new BTNode(2);
	root->right = new BTNode(3);
	root->left->left = new BTNode(4);
	root->left->right = new BTNode(5);
	root->right->left = new BTNode(6);
	root->right->right = new BTNode(7);
	int b = GetHeight(root);
	cout << b << endl;
	return 0;
}

你可能感兴趣的:(数据结构,数据结构,c++,算法)