forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 1
/
MinimumDepthOfBinaryTree.swift
39 lines (34 loc) · 1018 Bytes
/
MinimumDepthOfBinaryTree.swift
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
/**
* Question Link: https://leetcode.com/problems/minimum-depth-of-binary-tree/
* Primary idea: recursion, similar as maximum depth of a binary tree, need handle edge case first
* Time Complexity: O(n), Space Complexity: O(n)
*
* 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 MinimumDepthOfBinaryTree {
func minDepth(root: TreeNode?) -> Int {
guard let root = root else {
return 0
}
return _helper(root)
}
private func _helper(root: TreeNode?) -> Int {
guard let root = root else {
return Int.max
}
if root.left == nil && root.right == nil {
return 1
}
return min(_helper(root.left), _helper(root.right)) + 1
}
}