[leetcode]: 111. Minimum Depth of Binary Tree
来源:互联网 发布:医院数据库 编辑:程序博客网 时间:2024/06/15 09:43
1.题目
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.
求一棵二叉树的最小深度。
最小深度的定义为根节点到叶子节点的最小距离
2.分析
广度优先遍历,BFS。
相当于从根节点开始,一层一层往下遍历,当遍历到第一个叶子节点时,所得到的深度是最小的。
3.代码
BFS
class Solution {public: int minDepth(TreeNode* root) { if (root == NULL) return 0; queue<pair<TreeNode*,int>> nodes; nodes.push(make_pair(root, 1)); int depth = 0; while (!nodes.empty()) { TreeNode* node = nodes.front().first; depth = nodes.front().second; nodes.pop(); if (node->left) nodes.push(make_pair(node->left, depth + 1)); if (node->right) nodes.push(make_pair(node->right, depth + 1)); if (!node->left && !node->right)//叶子节点 return depth; } }};
阅读全文
0 0
- LeetCode 111. Minimum Depth of Binary Tree
- [LeetCode]111.Minimum Depth of Binary Tree
- 【LeetCode】111.Minimum Depth of Binary Tree
- [Leetcode] 111. Minimum Depth of Binary Tree
- [leetcode] 111. Minimum Depth of Binary Tree
- 111. Minimum Depth of Binary Tree LeetCode
- 【LeetCode】111. Minimum Depth of Binary Tree
- LeetCode *** 111. Minimum Depth of Binary Tree
- LeetCode 111. Minimum Depth of Binary Tree
- leetcode-111. Minimum Depth of Binary Tree
- LeetCode-111.Minimum Depth of Binary Tree
- LeetCode 111.Minimum Depth of Binary Tree
- Leetcode 111. Minimum Depth of Binary Tree
- [leetcode]111.Minimum Depth of Binary Tree
- 111.[Leetcode]Minimum Depth of Binary Tree
- LeetCode 111. Minimum Depth of Binary Tree
- 【leetcode】111. Minimum Depth of Binary Tree
- LeetCode 111. Minimum Depth of Binary Tree
- hibernate和mybatis缓存的对比
- servlet请求转发和重定向的区别
- 如何使用RED HAT CLOUDFORMS REST API 简述 (二)
- 买了阿里云之后
- 数据库连接池
- [leetcode]: 111. Minimum Depth of Binary Tree
- ibatis传入数组或List类型参数小结
- yoman脚手架 构建angular项目架构
- 数据驱动经济民生 浪潮大数据解决方案亮相数博会
- 关于打断设计的作用
- 输入任意5个整数,输出它们的和。
- JavaScript中常见的术语总结(如:什么是类?)
- B+树 ,B树,数据的搜索引擎
- 手动建栈维护最大值,用两个栈模拟队列!!