Problem:
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree is symmetric:
1 / \ 2 2 / \ / \ 3 4 4 3
But the following is not:
1 / \ 2 2 \ \ 3 3
Note:
Bonus points if you could solve it both recursively and iteratively.
Analysis:
Solutions:
C++:
bool isSymmetric(TreeNode *root) {
if(root == NULL)
return true;
queue<TreeNode *> left_subtree_visited;
TreeNode *pLeftCurrNode = root->left;
queue<TreeNode *> right_subtree_visited;
TreeNode *pRightCurrNode = root->right;
while(pLeftCurrNode != NULL || pRightCurrNode != NULL || !left_subtree_visited.empty() || !right_subtree_visited.empty()) {
if(pLeftCurrNode == NULL && pRightCurrNode == NULL) {
pLeftCurrNode = left_subtree_visited.front();
left_subtree_visited.pop();
pLeftCurrNode = pLeftCurrNode->right;
pRightCurrNode = right_subtree_visited.front();
right_subtree_visited.pop();
pRightCurrNode = pRightCurrNode->left;
} else if((pLeftCurrNode != NULL && pRightCurrNode == NULL)
|| (pLeftCurrNode == NULL && pRightCurrNode != NULL)
|| (pLeftCurrNode->val != pRightCurrNode->val)) {
return false;
} else {
left_subtree_visited.push(pLeftCurrNode);
pLeftCurrNode = pLeftCurrNode->left;
right_subtree_visited.push(pRightCurrNode);
pRightCurrNode = pRightCurrNode->right;
}
}
return true;
}
Java
:
Python: