题目描述:
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<TreeNode>();
LoadChildren(ref nodes, root);
if(nodes.Count == 0){
return layer;
}
layer ++;
MinDepth(nodes,ref layer);
return layer;
}
private void MinDepth(List<TreeNode> parents, ref int layer){
var next = new List<TreeNode>();
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<TreeNode> nodes, TreeNode node){
if(node.left != null){
nodes.Add(node.left);
}
if(node.right != null){
nodes.Add(node.right);
}
}
}