# 101. Symmetric Tree
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.
# Solution
Approach 1: Recursion.
Approach 2: Iteration. Roughly level order traversal (using a queue), but make sure 2 symmetric nodes go together so we can pop 2 nodes at once.
# Code (Python)
Approach 1:
def isSymmetric(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
# recursive
if not root:
return True
return self._is_symmetric(root.left, root.right)
def _is_symmetric(self, tree1, tree2):
if not tree1 and not tree2:
return True
if (tree1 or tree2) and not (tree1 and tree2):
return False
if tree1.val != tree2.val:
return False
return self._is_symmetric(tree1.left, tree2.right) and self._is_symmetric(tree1.right, tree2.left)
Approach 2:
def isSymmetric(self, root):
if not root:
return True
queue = deque([root.left, root.right])
while queue:
node1, node2 = queue.popleft(), queue.popleft()
if node1 and node2:
if node1.val != node2.val:
return False
else:
queue.append(node1.left)
queue.append(node2.right)
queue.append(node1.right)
queue.append(node2.left)
elif node1 or node2:
return False
return True
# Code (C++)
Approach 1:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isSymmetric(TreeNode* root) {
if (root == NULL) return true;
return isMirror(root->left, root->right);
}
bool isMirror(TreeNode *t1, TreeNode *t2) {
return (!t1 && !t2) ||
(t1 && t2 &&
t1->val == t2->val &&
isMirror(t1->left, t2->right) &&
isMirror(t1->right, t2->left));
}
};
Approach 2:
class Solution {
public:
bool isSymmetric(TreeNode* root) {
if (root == NULL) return true;
queue<TreeNode*> nodeQueue;
nodeQueue.push(root->left);
nodeQueue.push(root->right);
while (!nodeQueue.empty())
{
TreeNode *left = nodeQueue.front();
nodeQueue.pop();
TreeNode *right = nodeQueue.front();
nodeQueue.pop();
if (left == NULL && right == NULL) continue;
if (left == NULL || right == NULL) return false;
if (left->val != right->val) return false;
nodeQueue.push(left->left);
nodeQueue.push(right->right);
nodeQueue.push(left->right);
nodeQueue.push(right->left);
}
return true;
}
};