File tree Expand file tree Collapse file tree 1 file changed +36
-0
lines changed
maximum-depth-of-binary-tree Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments