二叉树的最小、最大深度

Leecode111 114二叉树的最小、最大深度

题目:

111:给定一个二叉树,找出其最小深度。

最小深度是从根节点到最近叶子节点的最短路径上的节点数量。

说明: 叶子节点是指没有子节点的节点。

示例:

给定二叉树 [3,9,20,null,null,15,7],

3

/ \

9 20

/ \

15 7

返回它的最小深度 2.

114:最大深度,同理;

思路:

  1. BFS:按层搜索,首次出现叶子节点的那一层层数就是最小深度,最后一层出现叶子节点的层数就是最大深度;

  2. DFS:找到每个叶子节点的层数,可得到最小深度和最大深度;

  3. 分治:如果同时存在左子树和右子树则,最小深度等于左子树和右子树中最小深度的最小值 + 1,否则等于存在的分支的最小深度 + 1;最大深度则等于左子树和右子树最大深度的较大值 + 1;

代码实现:

1,BFS:

private void bfs(TreeNode node){
	if(node  == null) return;
	Queue<TreeNode> queue = new LinkedList<>();
	queue.offer(node);
	int level = 0;
	while(!queue.isEmpty()){
	int size = queue.size(); //获取当前层的元素个数
	++level;
	for(int i =0 ;i < size;++i){ //取完当前层即结束循环,进入外层循环维护层数
                TreeNode nodeTemp = queue.poll();
                if(nodeTemp.left == null && nodeTemp.right == null){
                    min = min > level ? level : min;  //如果仅仅是找最小深度,则第一次找到就可以返回了,这里是最大最小深度都找了,所以没有返回
                    max = max > level ? max : level;
                }
                if(nodeTemp.left != null)
			queue.offer(nodeTemp.left);
                if(nodeTemp.right != null)
			queue.offer(nodeTemp.right);
		}
	 }
    }

2 DFS:

private void dfs(TreeNode node ,int level){
	if(node.left == null && node.right == null){
		min = min > level + 1 ? level + 1 : min;
		max = max > level + 1 ? max : level + 1;
		return;
	}
         //以下过滤条件在寻找最小深度时可以删除注释,能屏蔽一些不必要的分支,加快速度;最大深度不能有这个条件判断;
	// if(level >= min - 1){
	//   return;
	// }
	if(node.left != null)dfs(node.left,level+1);
	if(node.right != null)dfs(node.right,level+1);
    }
  1. 分治:
    最大深度:
class Solution {
	public int maxDepth(TreeNode root) {
		if(root == null) return 0;
		return Math.max(maxDepth(root.left),maxDepth(root.right)) + 1;
    }
}

最小深度:

 class Solution {
	int min = Integer.MAX_VALUE;
	int max = Integer.MIN_VALUE;
	public int minDepth(TreeNode root) {
		if(root == null) return 0;
		if(root.left != null && root.right != null){
		return Math.min(minDepth(root.left),minDepth(root.right)) + 1;
	}
	if(root.left != null){
		return minDepth(root.left)+1;
	}
	if(root.right != null){
		return minDepth(root.right) + 1;
	}
	return 1;
    }
} 
//或者写为以下代码,但上面的代码逻辑更为清晰;
class Solution {
	int min = Integer.MAX_VALUE;
	int max = Integer.MIN_VALUE;
	public int minDepth(TreeNode root) {
		if(root == null) return 0;
		int left = minDepth(root.left);
		int right = minDepth(root.right);
		return left == 0 || right == 0 ? left + right + 1 : Math.min(left,right)
+ 1;
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值