Leedcode1-求树的最小高度

2 篇文章 0 订阅
2 篇文章 0 订阅

#include<iostream>
#include<algorithm>
#include<queue>
using namespace std;
//5种情况:空树;没有子树;只有左/右子树;有俩子树;
struct BinaryNode {
	BinaryNode *left;
	BinaryNode *right;
	int data;
};
struct BinaryTree {
	BinaryNode *head;
};
//后序遍历递归
//如果左右子树都存在,则取其最小
//如果左右子树没有其中一个,-->说明此根下有叶子结点。所以取其最大
int getDepth(BinaryNode *node)
{
	if (node == NULL)
		return 0;
	int left_depth = getDepth(node->left);
	int right_depth = getDepth(node->right);
	if (left_depth && right_depth)  //左子树和右子树都存在
		return min(left_depth, right_depth) + 1;
	else
		return max(left_depth, right_depth) + 1;
}
//层次遍历,使用队列完成
int getDepth2(BinaryNode *root)
{
	if (root == NULL)
		return 0;
	queue<BinaryNode *>q;
	q.push(root);
	int depth = 0;
	while (!q.empty())   //q存放当前层结点,qt存放下一层结点
	{
		queue<BinaryNode *>qt;
		depth++;
		while (!q.empty())
		{
			BinaryNode *temp = q.front();
			cout << temp->data << endl;
			q.pop();
			if (!temp->left && !temp->right)
			{
				return depth;
			}
			if (temp->left)
				qt.push(temp->left);  
			if (temp->right)
				qt.push(temp->right);
		}
		q = qt;
	}
	return depth;
}

int main()
{
	/*
	      7
		/   \
	   8     9
	  /       \
	 4         10
	/ \
   2   5	
	*/
	BinaryTree btree;
	BinaryNode node1 = { NULL,NULL,7};
	BinaryNode node2 = { NULL,NULL,9 };
	BinaryNode node3 = { NULL,NULL,8 };
	BinaryNode node4 = { NULL,NULL,4 };
	BinaryNode node5 = { NULL,NULL,2 };
	BinaryNode node6 = { NULL,NULL,5 };
	BinaryNode node7 = { NULL,NULL,10 };
	btree.head = &(node1);
	node1.left = &(node3);
	node1.right = &(node2);
	node2.right = &(node7);
	node3.left = &(node4);
	node4.left = &(node5);
	node4.right = &(node6);
	int height = getDepth2(&(node1));
	cout << height << endl;

}

运行结果:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

chde2Wang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值