LeetCode-MinimumDepthOfBinaryTree
来源:互联网 发布:ubuntu恢复模式怎么用 编辑:程序博客网 时间:2024/06/05 07:41
题目:
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.
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */
分析:
查找二叉树的最小深度
分2种情况:
如果结点为NULL,返回0
否则,返回1+左右结点的最小深度
但这里有个地方需要注意,如果左右结点有一个为空,则应该返回1+另一个不为空的深度
如果左右节点都为空直接返回1
总结一下就是
if(l==0 || r==0) return 1+l+r;
AC代码
class Solution {public: int minDepth(TreeNode* root) { if(!root) return 0; int l = minDepth(root->left); int r = minDepth(root->right); if(l==0 || r==0) return 1+l+r; return 1+min(l,r); }};
阅读全文
0 0
- LeetCode-MinimumDepthOfBinaryTree
- LeetCode minimumDepthOfBinaryTree递归,迭代解析
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode
- leetcode:
- leetcode:
- LeetCode
- leetcode
- LEETCODE
- leetcode
- leetCode
- leetcode
- [leetcode]
- LeetCode
- leetcode
- nodejs环境快速搭建(centos,nvm)
- Tcpdump
- java鬼混笔记:nginx 负载均衡 简单配置
- map&reduce&filter
- Python文件操作
- LeetCode-MinimumDepthOfBinaryTree
- 链表相交问题【每日一题】
- X11 和Wayland的区别,一点感悟
- 数据库引擎简介
- 万年历
- python3 [爬虫入门实战]爬虫之scrapy爬取织梦者网站并存mongoDB
- JAVA面向对象6:多态
- C++总结5——继承与多态
- codeforces 722C Destroying Array 并查集带权