LeetCode -- Minimum Depth of Binary Tree
題目描述:
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.
就是求一個樹的最小層數。
思路:
從根節點進行BFS ,找到第一個葉子節點即可。
實現代碼:
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int MinDepth(TreeNode root)
{
if(root == null){
return 0;
}
var layer = 1;
var nodes = new List();
LoadChildren(ref nodes, root);
if(nodes.Count == 0){
return layer;
}
layer ++;
MinDepth(nodes,ref layer);
return layer;
}
private void MinDepth(List parents, ref int layer){
var next = new List();
for(var i = 0;i < parents.Count; i++){
if(parents[i].left == null && parents[i].right == null){
return;
}
if(parents[i].left != null){
next.Add(parents[i].left);
}
if(parents[i].right != null){
next.Add(parents[i].right);
}
}
layer ++;
MinDepth(next,ref layer);
}
private void LoadChildren(ref List nodes, TreeNode node){
if(node.left != null){
nodes.Add(node.left);
}
if(node.right != null){
nodes.Add(node.right);
}
}
}