-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0110.Balanced Binary Tree.swift
52 lines (44 loc) · 1.54 KB
/
0110.Balanced Binary Tree.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
/**
* Definition for a binary tree node.
* public class TreeNode {
* public var val: Int
* public var left: TreeNode?
* public var right: TreeNode?
* public init() { self.val = 0; self.left = nil; self.right = nil; }
* public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; }
* public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) {
* self.val = val
* self.left = left
* self.right = right
* }
* }
*/
class Solution {
func isBalanced(_ root: TreeNode?) -> Bool {
if root == nil {
return true
}
if root!.left == nil && root!.right == nil {
return true
}
if root!.left == nil && root!.right != nil && root!.right!.left == nil && root!.right!.right == nil {
return true
}
if root!.right == nil && root!.left != nil && root!.left!.left == nil && root!.left!.right == nil {
return true
}
let leftHeight = height(root!.left)
let rightHeight = height(root!.right)
let diff = max(leftHeight, rightHeight) - min(leftHeight, rightHeight)
return isBalanced(root!.left) && isBalanced(root!.right) && diff < 2
}
private func height(_ node: TreeNode?) -> Int {
if node == nil {
return 0
}
if node!.left == nil && node!.right == nil {
return 1
}
return max(height(node!.left), height(node!.right)) + 1
}
}