leetcodebfs-111

/** <p>給定一個二叉樹,找出其最小深度。</p> <p>最小深度是從根節點到最近葉子節點的最短路徑上的節點數量。</p> <p><strong>說明:</strong>葉子節點是指沒有子節點的節點。</p> <p> </p> <p><strong>示例 1:</strong></p> <img alt="" src="https://assets.leetcode.com/uploads/2020/10/12/ex_depth.jpg" style="width: 432px; height: 302px;" /> <pre> <strong>輸入:</strong>root = [3,9,20,null,null,15,7] <strong>輸出:</strong>2 </pre> <p><strong>示例 2:</strong></p> <pre> <strong>輸入:</strong>root = [2,null,3,null,4,null,5,null,6] <strong>輸出:</strong>5 </pre> <p> </p> <p><strong>提示:</strong></p> <ul> <li>樹中節點數的範圍在 <code>[0, 10<sup>5</sup>]</code> 內</li> <li><code>-1000 <= Node.val <= 1000</code></li> </ul> <div><div>Related Topics</div><div><li>樹</li><li>深度優先搜索</li><li>廣度優先搜索</li><li>二叉樹</li></div></div><br><div><li>👍 784</li><li>👎 0</li></div> */ //leetcode submit region begin(Prohibit modification and deletion) import java.util.LinkedList; import java.util.Queue; /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { //普通的bfs public int minDepth(TreeNode root) { if (root == null) { return 0; } Queue<TreeNode> queue = new LinkedList<>(); queue.offer(root); int depth = 1; while (!queue.isEmpty()) { int size = queue.size(); for (int i = 0; i < size; i++) { TreeNode poll = queue.poll(); if(poll.left==null && poll.right==null){ return depth; } if (poll.left != null) { queue.offer(poll.left); } if (poll.right != null) { queue.offer(poll.right); } } depth++; } return depth; } } //leetcode submit region end(Prohibit modification and deletion)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章