I'm trying to figure out if a tree is symmetrical iteratively. My approach consists of a level order traversal where I use two queues, the second one contains all the elements at each level and sends them to the isSymmetric function which uses that queue (q2) to figure out if the elements contained are palindromic. If they are not, then it returns false and the main function can return false.
The problem (and I suspect there's more than one - please do point them out!) is that the
node.left == null && node.right != null
and
arr[i] = current.remove().val;
give an OutOfBoundsException and I'm not sure why. Also, I'm creating a new TreeNode with the Integer.MIN_VALUE value if it's null because I want to account for the case when there are the same values on each side but not in the right positions.
Link to the question on leetcode: https://leetcode.com/problems/symmetric-tree/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean isSymmetric(TreeNode root) {
//bfs and each array in bfs should be palindromic
Queue<TreeNode> q = new LinkedList<>();
q.add(root);
boolean symmetric = false;
Queue<TreeNode> q2 = new LinkedList<>();
while(!q.isEmpty()) {
TreeNode node = q.remove();
if(node.left == null && node.right != null) {
q2.add(new TreeNode(Integer.MIN_VALUE));
}
else if(node.left != null && node.right == null) {
q2.add(new TreeNode(Integer.MIN_VALUE));
}
else {
q2.add(node.left);
q2.add(node.right);
}
if(q.isEmpty()) {
q = q2;
symmetric = isTreeSymmetric(q2);
if(symmetric == false) {
return false;
}
}
if(q2.isEmpty() && q.isEmpty()) {
return true;
}
}
return false;
}
public static boolean isTreeSymmetric(Queue<TreeNode> current) {
int[] arr = new int[current.size()];
System.out.println("current-size= " + current.size());
for(int i = 0; i < current.size(); i++) {
System.out.println(arr[i]);
arr[i] = current.remove().val;
}
int i = 0;
int j = current.size() - 1;
while(i < j) {
if(arr[i] != arr[j]) {
return false;
}
}
return true;
}
}