Minimum Depth of Binary Tree——LeetCode(Easy)
来源:互联网 发布:网络语斯什么意思 编辑:程序博客网 时间:2024/05/01 16:10
题目:Minimum Depth of Binary Tree
要求: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 binary tree * 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; } if (root->left == NULL && root->right == NULL) { return 1; } int minLeft = minDepth(root->left); int minRight = minDepth(root->right); if (minLeft == 0) return minRight+1; if (minRight == 0) return minLeft+1; return minLeft < minRight ? minLeft+1 : minRight+1; }};
觉得自己写的有点啰嗦,判定那一段写的不够精炼,在网上找了别人的代码比较一下:
class Solution { public: int minDepth(TreeNode *root) { // Start typing your C/C++ solution below // DO NOT write int main() function if(root) { if(root->left == NULL && root->right == NULL) return 1; else if(root->left == NULL) return minDepth(root->right) + 1; else if(root->right == NULL) return minDepth(root->left) + 1; return min(minDepth(root->left), minDepth(root->right)) + 1; } return 0; } };
看来代码这东西还是得多敲!
0 0
- Minimum Depth of Binary Tree——LeetCode(Easy)
- [Leetcode 104, Easy] Minimum (Maximum) Depth of Binary Tree
- [Leetcode 111, Easy] Minimum Depth of Binary Tree
- <LeetCode><Easy> 111 Minimum Depth of Binary Tree
- Leetcode 111. Minimum Depth of Binary Tree (Easy) (cpp)
- LeetCode解题报告 111. Minimum Depth of Binary Tree [easy]
- 【Leetcode-easy-111】Minimum Depth of Binary Tree
- LeetCode-Easy刷题(25) Minimum Depth of Binary Tree
- minimum-depth-of-binary-tree(Leetcode)
- LeetCode——Minimum Depth of Binary Tree
- 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
- LeetCode刷题(C++)——Minimum Depth if Binary Tree(Easy)
- LeetCode111—Minimum Depth of Binary Tree
- LeetCode刷题(C++)——Maximum Depth of Binary Tree(Easy)
- LeetCode: Minimum Depth of Binary Tree
- atitit.Atitit. Gui控件and面板-----服务端控件 java struts的实现最佳实践
- atitit.集合的filt操作细分 filter总结
- Android Messenger 进程间通信
- Atitit.解决org.hibernate.DuplicateMappingException: Duplicate class/entity mapping
- hdu_1506
- Minimum Depth of Binary Tree——LeetCode(Easy)
- 【Leetcode】Gray Code (Pascal)
- 最短路SPFA
- atitit.软件开发概念--过滤和投影 数据操作
- centos学习2-安装显卡驱动& VNC Server ---为了远程 centos6.4
- abs ,fabs
- C语言基础 函数
- JAVA8 十大新特性详解
- Myeclipse错误: 找不到或无法加载主类