111. Minimum Depth of Binary Tree
来源:互联网 发布:手机淘宝尺寸怎么设置 编辑:程序博客网 时间:2024/06/16 21:24
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, C++, 8ms, Beats 99.94% submissions
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: int minDepth(TreeNode* root) { if (root == NULL) return 0; queue<TreeNode*> qt; qt.push(root); int min = 0; while (!qt.empty()) { min++; for (int i=0,n=qt.size(); i<n;i++) { TreeNode* cur_node = qt.front(); if (cur_node->left) qt.push(cur_node->left); if (cur_node->right) qt.push(cur_node->right); qt.pop(); if (!cur_node->left && !cur_node->right) return min; } } return min; }};
递归
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: int minDepth(TreeNode* root) { if(!root) return 0; if(!root->left) return minDepth(root->right)+1; if(!root->right) return minDepth(root->left)+1; return 1+min(minDepth(root->left),minDepth(root->right)); }};
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
- 111.Minimum Depth of Binary Tree
- 111. Minimum Depth of Binary Tree
- [leetcode] 111. Minimum Depth of Binary Tree
- 111. Minimum Depth of Binary Tree
- 111. Minimum Depth of Binary Tree
- 111. Minimum Depth of Binary Tree
- 111. Minimum Depth of Binary Tree LeetCode
- 111. Minimum Depth of Binary Tree
- 111. Minimum Depth of Binary Tree
- 【LeetCode】111. Minimum Depth of Binary Tree
- 111. Minimum Depth of Binary Tree
- 111. Minimum Depth of Binary Tree
- LeetCode *** 111. Minimum Depth of Binary Tree
- 111. Minimum Depth of Binary Tree
- chm内容显示为空白的处理方法
- 资深C++程序员学习C#要点
- Cocos2dx 2.x移植安卓及打包
- (4.1.20.2)Android 5.0 可以给一个 View 单独设置一个 theme
- 一个介绍android 的log的一些进一步封装与快捷操作的文章
- 111. Minimum Depth of Binary Tree
- VS2013自带的数据库SQL Server Express LocalDB使用介绍
- 删除workspace空间的目录
- 软件开发模式对比:瀑布、迭代、螺旋、敏捷区别
- POJ 2955 Brackets 【区间DP】
- 显示指定文件中出现在另一个文件中的所有句子
- oracle编程
- 为什么程序员需要关心顺序一致性(Sequential Consistency)而不是Cache一致性(Cache Coherence?)
- Android学习笔记开篇