二叉树的最大、最小深度

思路

二叉树的最大和最小深度其实是一类问题,都可以用广度优先算法解决。我们可以在遍历的时候加入一个变量记录层级:

  • 当在循环过程中发现某个节点的左右子节点都为空,那它就是一个叶子节点,即可结束遍历,当前的层级数就是需要的最小深度
  • 当全部遍历完毕,此时的层级数即为最大深度

代码

这里将最大最小合并在一起写了,分别打印出来。

class Solution {
	public static void depth(Node root) {
		if (root != null) {
			LinkedList<Node> queue = new LinkedList();
			int level = 0;
			int minLevel = 0;
			queue.add(root);
			while (!queue.isEmpty()) {
				level++;
				int size = queue.size();
				for (int i = 0; i < size; i++) {
					Node current = queue.poll();
					if (current.left == null && current.right == null && minLevel == 0) {
						minLevel = level;
					}
					if (current.left != null) queue.add(current.left);
					if (current.right != null) queue.add(current.right);
				}
			}
			System.out.println("最小深度为:" + minLevel);
			System.out.println("最大深度为:" + level);
		}
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值