Skip to content

Commit 89ad43b

Browse files
committed
maximum depth of binary tree solution
1 parent 619ab5e commit 89ad43b

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* public class TreeNode {
4+
* public var val: Int
5+
* public var left: TreeNode?
6+
* public var right: TreeNode?
7+
* public init() { self.val = 0; self.left = nil; self.right = nil; }
8+
* public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; }
9+
* public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) {
10+
* self.val = val
11+
* self.left = left
12+
* self.right = right
13+
* }
14+
* }
15+
*/
16+
class Solution {
17+
func maxDepth(_ root: TreeNode?) -> Int {
18+
var result = 0
19+
20+
traverse(root, 0, &result)
21+
22+
return result
23+
}
24+
25+
func traverse(_ node: TreeNode?, _ current: Int, _ result: inout Int) {
26+
guard let node else {
27+
result = max(current, result)
28+
return
29+
}
30+
31+
let newCurrent = current + 1
32+
33+
traverse(node.left, newCurrent, &result)
34+
traverse(node.right, newCurrent, &result)
35+
}
36+
}

0 commit comments

Comments
 (0)