-
Notifications
You must be signed in to change notification settings - Fork 4
Open
Labels
Description
Question:
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.
Answer:
class Solution {
public:
bool isSymmetricPro(TreeNode *node1, TreeNode *node2){
if( node1 == NULL && node2 == NULL)
return true;
if( node1 == NULL || node2 == NULL || node1 -> val != node2 -> val)
return false;
return isSymmetricPro(node1 -> left, node2 -> right)&&isSymmetricPro(node1 -> right, node2 -> left);
}
bool isSymmetric(TreeNode* root) {
return (root == false )? true : isSymmetricPro( root -> left, root -> right);
}
};