Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 6215af4

Browse files
authored
Create
1 parent a9aa370 commit 6215af4

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

kotlin/0101-symmetric-tree.kt

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
/*
2+
* Recursive solution
3+
*/
4+
class Solution {
5+
fun isSymmetric(root: TreeNode?): Boolean {
6+
7+
fun dfs(left: TreeNode?, right: TreeNode?): Boolean {
8+
if(left == null && right == null)
9+
return true
10+
if(left == null || right == null)
11+
return false
12+
13+
return left.value == right.value &&
14+
dfs(left.left, right.right) &&
15+
dfs(left.right, right.left)
16+
}
17+
18+
return dfs(root!!.left, root!!.right)
19+
}
20+
21+
val TreeNode.value get()= this.`val`
22+
}
23+
24+
/*
25+
* Iterative solution
26+
*/
27+
class Solution {
28+
fun isSymmetric(root: TreeNode?): Boolean {
29+
val q = LinkedList<TreeNode?>()
30+
q.addFirst(root!!.left)
31+
q.addFirst(root!!.right)
32+
33+
while(q.isNotEmpty()) {
34+
val left = q.removeFirst()
35+
val right = q.removeFirst()
36+
37+
if(left == null && right == null)
38+
continue
39+
40+
if(left == null || right == null || left.value != right.value)
41+
return false
42+
43+
q.addFirst(left.left)
44+
q.addFirst(right.right)
45+
q.addFirst(left.right)
46+
q.addFirst(right.left)
47+
}
48+
49+
return true
50+
}
51+
52+
val TreeNode.value get()= this.`val`
53+
}

0 commit comments

Comments
 (0)