forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BalancedBinaryTree.swift
54 lines (47 loc) · 1.3 KB
/
BalancedBinaryTree.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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/**
* Question Link: https://leetcode.com/problems/balanced-binary-tree/
* Primary idea: use the idea of maximum depth of a binary tree
* 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 BalancedBinaryTree {
func isBalanced(root: TreeNode?) -> Bool {
guard let root = root else {
return true
}
if _checkHeight(root) == -1 {
return false
}
return true
}
private func _checkHeight(root: TreeNode?) -> Int {
guard let root = root else {
return 0
}
// check left and right subtree
var leftHeight = _checkHeight(root.left)
if leftHeight == -1 {
return -1
}
var rightHeight = _checkHeight(root.right)
if rightHeight == -1 {
return -1
}
// check current
if abs(leftHeight - rightHeight) > 1 {
return -1
}
return max(leftHeight, rightHeight) + 1
}
}