Skip to content

Commit 9f09a9d

Browse files
committed
feat: add python and java solutions to lcof problem
添加《剑指 Offer》题解:面试题55 - I. 二叉树的深度
1 parent 5ab9a5b commit 9f09a9d

File tree

3 files changed

+94
-0
lines changed

3 files changed

+94
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
# [面试题55 - I. 二叉树的深度](https://leetcode-cn.com/problems/er-cha-shu-de-shen-du-lcof/)
2+
3+
## 题目描述
4+
输入一棵二叉树的根节点,求该树的深度。从根节点到叶节点依次经过的节点(含根、叶节点)形成树的一条路径,最长路径的长度为树的深度。
5+
6+
例如:
7+
8+
给定二叉树 `[3,9,20,null,null,15,7]`
9+
10+
```
11+
3
12+
/ \
13+
9 20
14+
/ \
15+
15 7
16+
```
17+
18+
返回它的最大深度 3 。
19+
20+
**提示:**
21+
22+
- `节点总数 <= 10000`
23+
24+
## 解法
25+
### Python3
26+
```python
27+
# Definition for a binary tree node.
28+
# class TreeNode:
29+
# def __init__(self, x):
30+
# self.val = x
31+
# self.left = None
32+
# self.right = None
33+
34+
class Solution:
35+
def maxDepth(self, root: TreeNode) -> int:
36+
if root is None:
37+
return 0
38+
return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))
39+
```
40+
41+
### Java
42+
```java
43+
/**
44+
* Definition for a binary tree node.
45+
* public class TreeNode {
46+
* int val;
47+
* TreeNode left;
48+
* TreeNode right;
49+
* TreeNode(int x) { val = x; }
50+
* }
51+
*/
52+
class Solution {
53+
public int maxDepth(TreeNode root) {
54+
if (root == null) {
55+
return 0;
56+
}
57+
return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
58+
}
59+
}
60+
```
61+
62+
### ...
63+
```
64+
65+
```
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* public class TreeNode {
4+
* int val;
5+
* TreeNode left;
6+
* TreeNode right;
7+
* TreeNode(int x) { val = x; }
8+
* }
9+
*/
10+
class Solution {
11+
public int maxDepth(TreeNode root) {
12+
if (root == null) {
13+
return 0;
14+
}
15+
return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
16+
}
17+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
# Definition for a binary tree node.
2+
# class TreeNode:
3+
# def __init__(self, x):
4+
# self.val = x
5+
# self.left = None
6+
# self.right = None
7+
8+
class Solution:
9+
def maxDepth(self, root: TreeNode) -> int:
10+
if root is None:
11+
return 0
12+
return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))

0 commit comments

Comments
 (0)