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
递归,保存左右两个节点,然后判断leftNode->left和rightNode->right,以及leftNode->right和rightNode->left。如此不断递归
被这题坑了,本以为必须是满二叉树才行,其实不是,只要左右对称即可。
/**
* 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 check(root->left, root->right);
}
bool check(TreeNode* leftnode, TreeNode* rightnode)
{
if (leftnode == NULL && rightnode == NULL)
return true;
if (leftnode == NULL || rightnode == NULL)
return false;
if (leftnode->val != rightnode->val)
return false;
else
return check(leftnode->left, rightnode->right) && check(leftnode->right, rightnode->left);
}
};