-
-
Save InterviewBytes/b20b7a9cfa0b520fce1e1d26bac839b0 to your computer and use it in GitHub Desktop.
Iterative approach 2- Symmetric tree
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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