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 (recursive):
/**
* 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 isMirror(TreeNode* root1, TreeNode* root2) {
if ( root1 == NULL ) return (root2 == NULL );
if ( root2 == NULL ) return false;
if ( root1->val != root2->val ) return false;
if ( not isMirror(root1->left, root2->right) ) return false;
if ( not isMirror(root1->right, root2->left) ) return false;
return true;
}
bool isSymmetric(TreeNode* root) {
if ( root == NULL ) return true;
return (isMirror(root->left, root->right));
}
};
Solution (iterative):
/**
* 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;
// use level-ordere traversal result
vector<TreeNode*> res;
res.push_back(root->left);
res.push_back(root->right);
while ( res.size() != 0 ) {
int nres = res.size();
int i = 0, j = nres-1;
while ( i <= j-1 ) {
if ( res[i] == NULL and res[j] != NULL ) return false;
if ( res[i] != NULL and res[j] == NULL ) return false;
if ( res[i] == NULL and res[j] == NULL ) { i += 1; j -= 1; continue;}
if ( res[i]->val != res[j]->val ) return false;
i += 1;
j -= 1;
}
vector<TreeNode*> res2;
for ( i = 0; i <= nres-1; i++ ) {
if ( res[i] == NULL ) continue;
res2.push_back(res[i]->left);
res2.push_back(res[i]->right);
}
res = res2;
}
return true;
}
};