-
Notifications
You must be signed in to change notification settings - Fork 41
/
100.swift
77 lines (61 loc) · 1.75 KB
/
100.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
67
68
69
70
71
72
73
74
75
76
77
//
// SameTreeTest.swift
// LeetCode
//
// Created by Lex Tang on 5/6/15.
// Copyright (c) 2015 Lex Tang. All rights reserved.
//
/*
Given two binary trees, write a function to check if they are equal or not.
Two binary trees are considered equal if they are structurally identical and the nodes have the same value.
*/
import Foundation
import XCTest
private extension TreeNode {
func isEqualTo(_ tree: TreeNode) -> Bool {
if self.value != tree.value {
return false
}
var isEqual = true
if let l = self.leftNode, let tl = tree.leftNode {
if !l.isEqualTo(tl) {
isEqual = false
}
}
if let r = self.rightNode, let rl = tree.rightNode {
if !r.isEqualTo(rl) {
isEqual = false
}
}
return isEqual
}
}
func ==(lhs: TreeNode, rhs: TreeNode) -> Bool {
return lhs.isEqualTo(rhs)
}
class SameTreeTest: XCTestCase {
func testSameTree() {
XCTAssertTrue(TreeNode(0) == TreeNode(0), "")
let t0 = TreeNode(0, nil, TreeNode(2))
let t1 = TreeNode(0, nil, TreeNode(2))
XCTAssertTrue(t0 == t1, "")
let t2 = TreeNode(45,
TreeNode(2,
TreeNode(53,
TreeNode(1), TreeNode(2))))
let t3 = TreeNode(45,
TreeNode(2,
TreeNode(53,
TreeNode(1), TreeNode(2))))
XCTAssertTrue(t2 == t3, "")
let t4 = TreeNode(23,
TreeNode(4,
TreeNode(0), TreeNode(1)),
TreeNode(2))
let t5 = TreeNode(23,
TreeNode(4,
TreeNode(0), TreeNode(2)),
TreeNode(2))
XCTAssertFalse(t4 == t5, "")
}
}