Skip to content

Commit 676094f

Browse files
committed
feat: add the solution of Maximum Depth of Binary Tree(104) with kotlin.
1 parent 969983d commit 676094f

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

src/_104/kotlin/Solution.kt

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package _104.kotlin
2+
3+
import structure.TreeNode
4+
5+
/**
6+
* @author relish
7+
* @since 2018/04/26
8+
*
9+
* Definition for a binary tree node.
10+
* class TreeNode(var `val`: Int = 0) {
11+
* var left: TreeNode? = null
12+
* var right: TreeNode? = null
13+
* }
14+
*/
15+
class Solution {
16+
fun maxDepth(root: TreeNode?): Int {
17+
if (root == null) return 0
18+
if (root.left == null) return 1 + maxDepth(root.right)
19+
if (root.right == null) return 1 + maxDepth(root.left)
20+
return Math.max(1 + maxDepth(root.left), 1 + maxDepth(root.right))
21+
}
22+
}
23+
24+
fun main(args: Array<String>) {
25+
println(Solution().maxDepth(TreeNode.createTestData("[3,9,20,null,null,15,7]")))
26+
}

tips/104/README.md

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ The maximum depth is the number of nodes along the longest path from the root no
1313

1414
题意是找到二叉树的最大深度,很明显,深搜即可,每深入一次节点加一即可,然后取左右子树的最大深度。
1515

16+
Java:
1617
```java
1718
/**
1819
* Definition for a binary tree node.
@@ -31,6 +32,17 @@ The maximum depth is the number of nodes along the longest path from the root no
3132
}
3233
```
3334

35+
kotlin(212ms/100.00%):
36+
```kotlin
37+
class Solution {
38+
fun maxDepth(root: TreeNode?): Int {
39+
if (root == null) return 0
40+
if (root.left == null) return 1 + maxDepth(root.right)
41+
if (root.right == null) return 1 + maxDepth(root.left)
42+
return Math.max(1 + maxDepth(root.left), 1 + maxDepth(root.right))
43+
}
44+
}
45+
```
3446

3547
## 结语
3648

0 commit comments

Comments
 (0)