Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Iterative approach 2- Symmetric tree
package com.interviewbytes.trees;
import java.util.Deque;
import java.util.LinkedList;
public class SymmetricIterative2 {
public boolean isSymmetric(TreeNode root) {
if (root == null) return true;
Deque<TreeNode> queue = new LinkedList<>();
queue.offer(root.left);
queue.offer(root.right);
while (!queue.isEmpty()) {
TreeNode leftNode = queue.poll();
TreeNode rightNode = queue.poll();
if (leftNode == null && rightNode == null) continue;
if (leftNode == null || rightNode == null) return false;
if (leftNode.val != rightNode.val) return false;
queue.offer(leftNode.left);
queue.offer(rightNode.right);
queue.offer(leftNode.right);
queue.offer(rightNode.left);
}
return true;
}
}
package com.interviewbytes.trees;
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.