LeetCode -- Minimum Depth of Binary Tree
2015-11-29 22:46
232 查看
题目描述:
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 ,找到第一个叶子节点即可。
实现代码:
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); } } }
相关文章推荐
- Eclipse开发C/C++ 安装配置图文详解
- 程序员瞎扯,扯得很有道理
- codeforces 601C (概率DP)
- Object Detection Networks on Convolutional Feature Maps
- LeetCode -- Maximum Subarray
- Matlab的plot~各种颜色和线形
- Java中一些常用的正则表达式
- linux 查找svn相关目录
- Linux内核之中断初探
- Linux configure 参数解释
- Git冲突处理的一些经验
- WebKit之addToJavaScriptWindowObject()分析
- jqgrid引用
- Merge Intervals
- PAT甲级1001
- 开源项目9GAG源码解析与Material改造(三)
- Android 使用SystemBarTint设置状态栏颜色
- Android 使用SystemBarTint设置状态栏颜色
- linux-文件系统管理03-LVM硬盘管理
- 开发笔记 - 自定义推送声音