問題:
Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
大意:
給出一個二叉樹,找到他最小的深度。
最小的深度是指從根節點到葉子節點距離最短的節點數。
思路:
這道題要找到最短的深度,個人認為更應該用廣度優先遍歷來做,一層一層地掃過去,哪一層有葉子節點了,就不掃了,把深度返回來。如果用深度優先遍歷,每一條路都要走完,要所有路徑都走到最后才能確定最短的。
廣度優先取一個隊列來記錄每一層的節點數,利用隊列先進先出的特性,一層層掃,每次掃到下一層的都加到隊尾,把當前層的個數掃完后就將層數加一,直到找到葉子節點就直接返回當前找的深度。
代碼(Java):
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int minDepth(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<TreeNode>();
if (root == null) return 0;
int result = 1;
queue.offer(root);
while (!queue.isEmpty()) {
int levelNum = queue.size();
for (int i = 0; i < levelNum; i++) {
if (queue.peek().left == null && queue.peek().right == null) return result;
if (queue.peek().left != null) queue.offer(queue.peek().left);
if (queue.peek().right != null) queue.offer(queue.peek().right);
queue.poll();
}
result++;
}
return result;
}
}
合集:https://github.com/Cloudox/LeetCode-Record