Skip to content

Commit aa1859e

Browse files
Add files via upload
1 parent d42bf84 commit aa1859e

File tree

2 files changed

+63
-0
lines changed

2 files changed

+63
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
// 第一种思路 二叉树的最小高度等于 左右子树的最小高度+1 但是要注意多一个判断条件
2+
// 8ms 53.51%
3+
4+
/**
5+
* Definition for a binary tree node.
6+
* struct TreeNode {
7+
* int val;
8+
* TreeNode *left;
9+
* TreeNode *right;
10+
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
11+
* };
12+
*/
13+
class Solution {
14+
public:
15+
int minDepth(TreeNode* root) {
16+
17+
if (!root)
18+
return 0;
19+
if (!root->left && !root->right)
20+
return 1;
21+
22+
int depthLeft = minDepth(root->left);
23+
int depthRight = minDepth(root->right);
24+
25+
if (!depthLeft)
26+
return depthRight + 1;
27+
else if (!depthRight)
28+
return depthLeft + 1;
29+
else
30+
return depthLeft < depthRight ? depthLeft + 1: depthRight + 1;
31+
}
32+
};
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# 第一种思路 二叉树的最小高度等于 左右子树的最小高度+1 但是要注意多一个判断条件
2+
# 76ms 33.76%
3+
4+
# Definition for a binary tree node.
5+
# class TreeNode:
6+
# def __init__(self, x):
7+
# self.val = x
8+
# self.left = None
9+
# self.right = None
10+
11+
class Solution:
12+
def minDepth(self, root):
13+
"""
14+
:type root: TreeNode
15+
:rtype: int
16+
"""
17+
18+
if root is None:
19+
return 0
20+
if root.left is None and root.right is None:
21+
return 1
22+
23+
depthLeft = self.minDepth(root.left)
24+
depthRight = self.minDepth(root.right)
25+
26+
if depthLeft is 0 or depthRight is 0:
27+
return max(depthLeft, depthRight) + 1
28+
else:
29+
return min(depthLeft, depthRight) + 1
30+
31+

0 commit comments

Comments
 (0)