Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree
[1,2,2,3,4,4,3]
is symmetric:1 / \ 2 2 / \ / \ 3 4 4 3
But the following
[1,2,2,null,3,null,3]
is not:1 / \ 2 2 \ \ 3 3
Note:
Bonus points if you could solve it both recursively and iteratively.
For this problem I want to record the iterative solution.
Recusive:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isSymmetric(TreeNode root) {
if(root==null) return true;
return helper(root.left, root.right);
}
public boolean helper(TreeNode lt, TreeNode rt) {
if(lt==null||rt==null) return (rt==lt);
if(lt.val==rt.val) return helper(lt.left, rt.right)&&helper(lt.right, rt.left);
return false;
}
}
Iterative:
The below solution is BFS and iterative.
In Queue
(LinkedList
) , we use Queue.offer(element)
to insert (will not throw Null exception) and Queue.poll()
to pop the top element.
public class Solution {
public boolean isSymmetric(TreeNode root) {
if (root == null || root.left == null && root.right == null){
return true;
}
if (root.left == null || root.right == null){
return false;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root.left);
queue.offer(root.right);
while (!queue.isEmpty()) {
TreeNode left = queue.poll();
TreeNode right = queue.poll();
if (left.val != right.val){
return false;
}
if (left.left != null && right.right != null){
queue.offer(left.left);
queue.offer(right.right);
}
else if (left.left == null && right.right != null || right.right == null && left.left != null){
return false;
}
if (left.right != null && right.left != null){
queue.offer(left.right);
queue.offer(right.left);
}
else if (left.right == null && right.left != null || right.left == null && left.right != null){
return false;
}
}
return true;
}
}