本题题目要求如下:
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.
本题只要保证遍历所有的点,且每个点与其mirror后的点都相同就行。。
起始是比较左2和右2,他们俩是第一对对称点,如果相同,则比较他俩引申的对称点。。即(左2)的左child和右二的右child,左2的右child和右2的左child,这样不停地遍历,就能访问所有点,代码如下:
/**
* Definition for binary tree
* 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;
else
return isSymmetric(root->left, root->right);
}
private:
bool isSymmetric(TreeNode* root1, TreeNode* root2) {
if (root1 == NULL and root2 == NULL)
return true;
else if (root1 != NULL and root2 != NULL) {
if (root1->val == root2->val)
return isSymmetric(root1->left, root2->right) and isSymmetric(root1->right, root2->left);
else
return false;
}
else
return false;
}
};