题目:
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
分析:
递归,保存左右两个节点,然后判断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) return true;
return compRoot(root -> left, root -> right);
}
private:
bool compRoot(TreeNode* lroot, TreeNode* rroot){
if(!lroot) return (NULL == rroot);
if(NULL == rroot) return false;
if(lroot -> val != rroot -> val) return false;
return (compRoot(lroot -> left, rroot -> right) && compRoot(lroot -> right, rroot -> left));
}
};