Minimum Depth of Binary Tree——LeetCode(Easy)
2014-11-10 00:07
477 查看
题目: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.
意思就是寻找二叉树里面的最小路径
我自己写的代码如下:
觉得自己写的有点啰嗦,判定那一段写的不够精炼,在网上找了别人的代码比较一下:
看来代码这东西还是得多敲!
要求: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; } };
看来代码这东西还是得多敲!
相关文章推荐
- 【Leetcode】【Easy】Minimum Depth of Binary Tree
- 【Leetcode-easy-111】Minimum Depth of Binary Tree
- leetcode_题解_Minimum Depth of Binary Tree _easy需细心
- LeetCode:111_Minimum Depth of Binary Tree | 二叉树的最小深度 | Easy
- [Leetcode 111, Easy] Minimum Depth of Binary Tree
- [Leetcode 104, Easy] Minimum (Maximum) Depth of Binary Tree
- 【leetcode】Minimum Depth of Binary Tree (easy)
- 【LeetCode】Minimum Depth Of Binary Tree二叉树的最小深度 - Easy
- [LeetCode] Minimum Depth of Binary Tree - BFS
- [LeetCode 111] - 二叉树的最小深度 (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 31: 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