mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
Create 111. Minimum Depth of Binary Tree.md
This commit is contained in:
parent
82bf920b54
commit
dd8fa6310b
21
111. Minimum Depth of Binary Tree.md
Normal file
21
111. Minimum Depth of Binary Tree.md
Normal file
@ -0,0 +1,21 @@
|
|||||||
|
# [111. Minimum Depth of Binary Tree](https://leetcode.com/problems/minimum-depth-of-binary-tree/description/)
|
||||||
|
# 思路
|
||||||
|
求二叉树的最小深度。依次分为以下情况:
|
||||||
|
* 若为空树,则返回0;
|
||||||
|
* 否则,若左右子树都为空,返回1;
|
||||||
|
* 否则,若左子树为空,那么最小深度就为右子树的最小深度加1;若右子树为空,那么最小深度就为左子树的最小深度加1;
|
||||||
|
* 否则(即左右子树都不空),那么最小深度就是min(1+左子树最小深度, 1+右子树最小深度);
|
||||||
|
|
||||||
|
# C++
|
||||||
|
``` C++
|
||||||
|
class Solution {
|
||||||
|
public:
|
||||||
|
int minDepth(TreeNode* root) {
|
||||||
|
if(root == NULL) return 0;
|
||||||
|
else if(root -> left == NULL && root -> right == NULL) return 1;
|
||||||
|
else if(root -> left == NULL) return 1 + minDepth(root -> right);
|
||||||
|
else if(root -> right == NULL) return 1 + minDepth(root -> left);
|
||||||
|
return 1 + min(minDepth(root -> left), minDepth(root -> right));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
```
|
Loading…
Reference in New Issue
Block a user