-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0101-symmetric-tree.kt
53 lines (42 loc) · 1.24 KB
/
0101-symmetric-tree.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
/*
* Recursive solution
*/
class Solution {
fun isSymmetric(root: TreeNode?): Boolean {
fun dfs(left: TreeNode?, right: TreeNode?): Boolean {
if(left == null && right == null)
return true
if(left == null || right == null)
return false
return left.value == right.value &&
dfs(left.left, right.right) &&
dfs(left.right, right.left)
}
return dfs(root!!.left, root!!.right)
}
val TreeNode.value get()= this.`val`
}
/*
* Iterative solution
*/
class Solution {
fun isSymmetric(root: TreeNode?): Boolean {
val q = LinkedList<TreeNode?>()
q.addFirst(root!!.left)
q.addFirst(root!!.right)
while(q.isNotEmpty()) {
val left = q.removeFirst()
val right = q.removeFirst()
if(left == null && right == null)
continue
if(left == null || right == null || left.value != right.value)
return false
q.addFirst(left.left)
q.addFirst(right.right)
q.addFirst(left.right)
q.addFirst(right.left)
}
return true
}
val TreeNode.value get()= this.`val`
}