-
Notifications
You must be signed in to change notification settings - Fork 41
/
110.swift
66 lines (49 loc) · 1.59 KB
/
110.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
55
56
57
58
59
60
61
62
63
64
65
66
//
// 110.swift
// LeetCode
//
// Created by Lex on 12/29/15.
// Copyright © 2015 Lex Tang. All rights reserved.
//
/*
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
*/
import Foundation
import XCTest
extension TreeNode {
fileprivate func getHeight(_ node: TreeNode?) -> Int {
guard let node = node else {
return 0
}
if node.leftNode == nil && node.rightNode == nil {
return 0
}
let leftHeight = getHeight(node.leftNode)
let rightHeight = getHeight(node.rightNode)
let distance = leftHeight > rightHeight
? leftHeight - rightHeight
: rightHeight - leftHeight
if distance > 1 {
return -1
}
return distance + 1
}
func isBalancedBinaryTree() -> Bool {
return getHeight(self) != -1
}
}
class BalancedBinaryTreeTest: XCTestCase {
func testBalancedBinaryTree() {
var tree = TreeNode(0, TreeNode(1), TreeNode(0, TreeNode(2)))
XCTAssert(tree.isBalancedBinaryTree())
tree = TreeNode()
XCTAssert(tree.isBalancedBinaryTree())
tree = TreeNode(0, TreeNode(1), TreeNode(0, TreeNode(2, TreeNode(3))))
XCTAssert(!tree.isBalancedBinaryTree())
tree = TreeNode(2, TreeNode(2), nil)
XCTAssert(tree.isBalancedBinaryTree())
tree = TreeNode(2, TreeNode(2), TreeNode(2))
XCTAssert(tree.isBalancedBinaryTree())
}
}