-
Notifications
You must be signed in to change notification settings - Fork 41
/
101.swift
78 lines (56 loc) · 1.46 KB
/
101.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
78
//
// SymmetricTreeTest.swift
// LeetCode
//
// Created by Lex Tang on 6/16/15.
// Copyright (c) 2015 Lex Tang. All rights reserved.
//
/*
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree is symmetric:
1
/ \
2 2
/ \ / \
3 4 4 3
But the following is not:
1
/ \
2 2
\ \
3 3
Note:
Bonus points if you could solve it both recursively and iteratively.
*/
import Foundation
import XCTest
func isNodesSymmetric(_ left: TreeNode?, right: TreeNode?) -> Bool {
if left == nil && right == nil {
return true
}
if left == nil || right == nil {
return false
}
if left!.value != right!.value {
return false
}
return isNodesSymmetric(left!.leftNode, right: right!.rightNode)
&& isNodesSymmetric(right!.leftNode, right: left!.rightNode)
}
func isSymmetric(_ root: TreeNode?) -> Bool {
if root == nil {
return true
}
return isNodesSymmetric(root!.leftNode, right: root!.rightNode)
}
class SymmetricTreeTest: XCTestCase {
func testSymmetricTree() {
XCTAssertTrue(isSymmetric(nil), "")
let t0 = TreeNode(1,
TreeNode(2, TreeNode(3), TreeNode(4)), TreeNode(2, TreeNode(4), TreeNode(3)))
XCTAssertTrue(isSymmetric(t0), "")
let t1 = TreeNode(1,
TreeNode(2, nil, TreeNode(3)), TreeNode(2, nil, TreeNode(3)))
XCTAssertFalse(isSymmetric(t1), "")
}
}