题目
思路
如果对称,对于一个节点来说,假设这个节点非空,那么必须满足:
cur->left和cur->right首先数值相同
cur->left->left和cur->right->right相同
cur->left->right和cur->right->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 judge(TreeNode* leftNode, TreeNode * rightNode){
if(leftNode == NULL && rightNode == NULL) return true;
if(leftNode == NULL && rightNode != NULL) return false;
if(leftNode != NULL && rightNode == NULL) return false;
if(leftNode->val != rightNode->val) return false;
return judge(leftNode->left, rightNode->right) && judge(leftNode->right, rightNode->left);
}
bool isSymmetric(TreeNode* root) {
return ( root== NULL || judge(root->left, root->right) );
}
};