Skip to content

Commit cdb2e20

Browse files
Add files via upload
1 parent d58d8c8 commit cdb2e20

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
// 思路一 二叉树的高度等于 max(depth(左子树), depth(右子树)) + 1 利用递归求解
2+
// 4ms 98.96%
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 maxDepth(TreeNode* root) {
16+
if (!root)
17+
return 0;
18+
else if (!root->left && !root->right)
19+
return 1;
20+
else
21+
{
22+
int depthLeft = maxDepth(root->left);
23+
int depthRight = maxDepth(root->right);
24+
return depthLeft > depthRight ? depthLeft + 1 : depthRight + 1;
25+
}
26+
}
27+
};
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
# 思路一 二叉树的高度等于 max(depth(左子树), depth(右子树)) + 1 利用递归求解
2+
# 72ms 35.60%
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 maxDepth(self, root):
13+
"""
14+
:type root: TreeNode
15+
:rtype: int
16+
"""
17+
if root is None:
18+
return 0
19+
20+
if root.left is None and root.right is None:
21+
return 1
22+
23+
return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1

0 commit comments

Comments
 (0)