0
点赞
收藏
分享

微信扫一扫

2021-08-06

夜空一星 2022-03-11 阅读 80

1.递归

#include<iostream>
using namespace std;
#define MAX 15

typedef struct treenode
{
	char data;
	struct treenode* lchild, * rchild;
}BiTNode,*BiTree;
void build___tree(BiTree& t)
{
	char ch = getchar();
	if (ch == '#')
		t = NULL;
	else
	{
		t = (BiTree)malloc(sizeof(BiTNode));
		t->data = ch;
		t->lchild = NULL;
		t->rchild = NULL;
		build___tree(t->lchild);
		build___tree(t->rchild);
	}
}
void _print(BiTree t)
{
	if (t)
	{
		cout << t->data << " ";
		_print(t->lchild);
		_print(t->rchild);
	}
}
int _depth(BiTree t)
{
	if (!t)
		return 0;
	int left_depth = _depth(t->lchild);
	int right_depth = _depth(t->rchild);
	return fmax(left_depth, right_depth) + 1;
}
int main()
{
	BiTree t;
	build___tree(t);
	cout << "前序:" << endl;
	_print(t);
	cout << endl;
	cout << "树高:" << _depth(t);
}

2.非递归–辅助队–结点指针 max(层)=高度
每一层遍历到最右边+1

#include<iostream>
using namespace std;
#define MAX 15
typedef struct treenode
{
	char data;
	struct treenode* lchild, * rchild;
}BiNode,*BiTree;

void build__Tree(BiTree& t)
{
	char data;
	data = getchar();
	if (data == '#')
		t = NULL;
	else
	{
		t = (treenode*)malloc(sizeof(treenode));
		t->data = data;
		t->lchild = NULL;
		t->rchild = NULL;
		build__Tree(t->lchild);
		build__Tree(t->rchild);
	}
}
void print(BiTree t)
{
	if (t)
	{
		cout << t->data << " ";
		print(t->lchild);
		print(t->rchild);
	}
}
int depth(BiTree t)
{
	if (!t)
		return 0;
	int front = -1, rear = -1;
	int L = 0, ans = 0;
	BiTree q[MAX];
	BiTree p;
	q[++rear] = t;
	while (front < rear)
	{
		p = q[++front];
		if(p->lchild)
			q[++rear]=p->lchild;
		if(p->rchild)
			q[++rear] = p->rchild;
		if (L == front)
		{
			ans++;
			L = rear;
		}
	}
	return ans;
}
int main()
{
	BiTree t;
	build__Tree(t);
	cout << "前序序列:" << endl;
	print(t); cout << endl;
	cout << "层高为:" << depth(t);
	return EXIT_SUCCESS;
}

运行结果:
在这里插入图片描述

举报

相关推荐

0 条评论