-
Notifications
You must be signed in to change notification settings - Fork 0
/
SymmetricTree.kt
102 lines (82 loc) · 2.92 KB
/
SymmetricTree.kt
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package problems
import java.util.*
class SymmetricTree {
class TreeNode(var `val`: Int) {
var left: TreeNode? = null
var right: TreeNode? = null
}
//By Queue; inspired by Breadth First Search (aka Command and Conquer), Most Optimal in terms of memory.
fun isSymmetricQueue(root: TreeNode?): Boolean {
val q: Queue<TreeNode?> = LinkedList()
q.poll()
q.add(root)
q.add(root)
while (!q.isEmpty()) {
val t1 = q.poll()
val t2 = q.poll()
if (t1 == null && t2 == null) continue
if (t1 == null || t2 == null) return false
if (t1.`val` != t2.`val`) return false
q.add(t1.left)
q.add(t2.right)
q.add(t1.right)
q.add(t2.left)
q.forEach { print("${it?.`val`}, " ) }
println("")
}
return true
}
//By recursive
//For first call, pass in same root node.
fun isMirror(t1: TreeNode?, t2: TreeNode?): Boolean {
if (t1 == null && t2 == null) return true
if (t1 == null || t2 == null) return false
return t1.`val` == t2.`val` && isMirror(t1.right, t2.left) && isMirror(t1.left, t2.right)
}
//Stack
fun isSymmetricStack(root: TreeNode?): Boolean {
val stackLeft = Stack<TreeNode>()
val stackRight = Stack<TreeNode>()
var currLeft: TreeNode? = root?.left
var currRight: TreeNode? = root?.right
while (currLeft != null || !stackLeft.isEmpty() || currRight != null || !stackRight.isEmpty()) {
while (currLeft != null || currRight != null) {
if (currLeft?.`val` != currRight?.`val`) return false
stackLeft.push(currLeft)
stackRight.push(currRight)
currLeft = currLeft?.left
currRight = currRight?.right
}
currLeft = stackLeft.pop()
currRight = stackRight.pop()
if (currLeft?.`val` != currRight?.`val`) return false
currLeft = currLeft?.right
currRight = currRight?.left
}
return true
}
fun tester() {
//[1,99,2,3]
val root = TreeNode(1)
root.left = TreeNode(2)
root.left?.right = TreeNode(3)
root.right = TreeNode(2)
root.right?.right = TreeNode(3)
//1,2,2,3,4,4,3
val root2 = TreeNode(1)
root2.left = TreeNode(2)
root2.left?.left = TreeNode(3)
root2.left?.right = TreeNode(4)
root2.right = TreeNode(2)
root2.right?.left = TreeNode(4)
root2.right?.right = TreeNode(3)
val root3 = TreeNode(1)
root3.left = TreeNode(2)
root3.left?.left = TreeNode(31)
root3.left?.right = TreeNode(32)
root3.right = TreeNode(2)
root3.right?.left = TreeNode(33)
root3.right?.right = TreeNode(34)
println(isSymmetricQueue(root3))
}
}