leetcode:Minimum Depth of Binary Tree
来源:互联网 发布:库里2016常规赛数据 编辑:程序博客网 时间:2024/06/05 10:40
题目描述:
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.(从根节点到叶节点经过的最短路径经过的节点数)
实现:
1.递归
class Solution {public: int run(TreeNode *root) { if(root==NULL) return 0; int depthl=run(root->left); int depthr=run(root->right); if(depthl==0&&depthr==0) return 1; if(depthl==0) depthl=INT_MAX;//没有左节点一定不是该路径 if(depthr==0) depthr=INT_MAX; return min(depthl,depthr)+1; }};2.非递归
按广度优先遍历(按层次遍历),若某一层出现了叶节点就返回其深度。
int run(TreeNode *root) { queue<pair<TreeNode*, int>> q; if(root == NULL) return 0; q.push(make_pair(root,1)); while(!q.empty()){ pair<TreeNode*, int> cur = q.front(); q.pop(); if(!cur.first->left && !cur.first->right) return cur.second; if(cur.first->left) q.push(make_pair(cur.first->left,cur.second+1)); if(cur.first->right) q.push(make_pair(cur.first->right,cur.second+1)); }}其中用到了STL容器类。
0 0
- LeetCode: Minimum Depth of Binary Tree
- [Leetcode] Minimum Depth of Binary Tree
- LeetCode : Minimum Depth of Binary Tree
- leetcode 31: Minimum Depth of Binary Tree
- [LeetCode] Minimum Depth of Binary Tree - BFS
- [LeetCode] Minimum Depth of Binary Tree - DFS
- 【leetcode】Minimum Depth of Binary Tree
- LeetCode:Minimum Depth of Binary Tree
- [LeetCode]Minimum Depth of Binary Tree
- [Leetcode]Minimum Depth of Binary Tree
- [leetcode]Minimum Depth of Binary Tree
- Leetcode: Minimum Depth of Binary Tree
- LeetCode-Minimum Depth of Binary Tree
- [leetcode] Minimum Depth of Binary Tree
- LeetCode - Minimum Depth of Binary Tree
- 【Leetcode】Minimum Depth of Binary Tree
- LeetCode | Minimum Depth of Binary Tree
- LeetCode - Minimum Depth of Binary Tree
- XPath提取XML文档数据
- VS2015 C++/CLR
- LaTex简历模板 Using the LaTeX Resume Templates
- Java使用多线程导入数据到Oracle中
- LaTex初学者模板
- leetcode:Minimum Depth of Binary Tree
- Google I/O大会,炫酷产品汇总
- C++菱形继承
- BaseActivity与BaseFragment的封装
- iOS 证书导出为p12,再导入其他电脑只能导入其中一个的解决方法
- 第107课: Spark Streaming电商广告点击综合案例底层数据层的建模和编码实现(基于MySQL)
- BSG白山极客挑战赛-A-数数字
- sor文件分析软件
- 啦啦啦啦~Django1.96---编写第一个Django应用(6)