bfs模板总结

编程入门 行业动态 更新时间:2024-10-23 23:20:38

bfs<a href=https://www.elefans.com/category/jswz/34/1770549.html style=模板总结"/>

bfs模板总结

bfs模板总结

bfs以及dfs都是蓝桥杯常考题

以下以LeetCode111.二叉树的最小深度

最小深度就是当存在结点没有孩子结点就返回

 //最小深度bfs经典模板
class Solution {public int minDepth(TreeNode root) {Queue<TreeNode> que = new LinkedList<>();if(root == null) return 0;que.offer(root);int depth = 0;while(!que.isEmpty()){depth++;int size = que.size();while(size > 0){size--;TreeNode cur = que.poll();if(cur.left != null) que.offer(cur.left);if(cur.right != null) que.offer(cur.right);if(cur.left == null && cur.right == null) return depth;}}return depth;}
}

对比:LeetCode 104. 二叉树的最大深度

/

与最小深度唯一的不同就是去掉了

if(cur.left == null && cur.right == null) return depth;这一行,因为最大深度就是要遍历每一层 直接套用层次遍历模板遍历完即可

//使用bfs模板解public int maxDepth(TreeNode root) {Queue<TreeNode> que = new LinkedList<>();if(root == null) return 0;que.offer(root);int depth = 0;while(!que.isEmpty()){depth++;int size = que.size();while(size > 0){size--;TreeNode cur = que.poll();if(cur.left != null) que.offer(cur.left);if(cur.right != null) que.offer(cur.right);// if(cur.left == null && cur.right == null) return depth;}}return depth;}

更新中…

更多推荐

bfs模板总结

本文发布于:2024-02-26 17:07:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1703268.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:模板   bfs

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!