forked from yuyongwei/Algorithms-In-Swift
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmaximumDepthOfBinaryTree.swift
More file actions
55 lines (40 loc) · 1.14 KB
/
Copy pathmaximumDepthOfBinaryTree.swift
File metadata and controls
55 lines (40 loc) · 1.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/*
Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Note: A leaf is a node with no children.
Example:
Given binary tree [3,9,20,null,null,15,7],
return its depth = 3.
https://leetcode.com/problems/maximum-depth-of-binary-tree/
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* public var val: Int
* public var left: TreeNode?
* public var right: TreeNode?
* public init(_ val: Int) {
* self.val = val
* self.left = nil
* self.right = nil
* }
* }
*/
class Solution {
func maxDepth(_ root: TreeNode?) -> Int {
guard let root = root else { return 0 }
return dfs(root, 1)
}
func dfs(_ node: TreeNode, _ level: Int) -> Int {
if node.left == nil && node.right == nil { return level }
var ll = level
var lr = level
if let left = node.left {
ll = dfs(left, level+1)
}
if let right = node.right {
lr = dfs(right, level+1)
}
return max(ll, lr)
}
}