-
-
Notifications
You must be signed in to change notification settings - Fork 12
/
symmetric-tree.java
50 lines (48 loc) · 1.33 KB
/
symmetric-tree.java
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
import java.util.*;
/**
* Problem: https://leetcode.com/problems/symmetric-tree/
*
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isSymmetric(TreeNode root) {
if (root == null) return true;
Queue<TreeNode> q = new LinkedList<TreeNode>();
String left = "";
if (root.left == null) left = ",#";
else {
q.add(root.left);
while(!q.isEmpty()) {
TreeNode node = q.poll();
if(node == null) left += ",#";
else {
left += ","+node.val;
q.add(node.left);
q.add(node.right);
}
}
}
q.clear();
String right = "";
if (root.right == null) right = ",#";
else {
q.add(root.right);
while(!q.isEmpty()) {
TreeNode node = q.poll();
if(node == null) right += ",#";
else {
right += ","+node.val;
q.add(node.right);
q.add(node.left);
}
}
}
return left.compareTo(right) == 0;
}
}