您的位置:首页 > 其它

LeetCode111 Minimum Depth of Binary Tree

2016-11-08 22:22 344 查看
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. (Easy)

分析:

注意题目中定义的最短深度是从根节点到叶子节点的最短长度。所以到空节点返回0,且当有一个子节点为空,另一个不空时,那个点不是叶子节点,不能算作最深的一层。

代码:

1 class Solution {
2 public:
3     int minDepth(TreeNode* root) {
4         if (root == nullptr) {
5             return 0;
6         }
7         if (root -> left != nullptr && root -> right != nullptr) {
8             return min(minDepth(root->left), minDepth(root->right)) + 1;
9         }
10         else if (root -> left != nullptr) {
11             return minDepth(root->left) + 1;
12         }
13         return minDepth(root -> right) + 1;
14
15     }
16 };
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: