题目

请实现一个函数,用来判断一棵二叉树是不是对称的。如果一棵二叉树和它的镜像一样,那么它是对称的。

例如,二叉树 [1, 2, 2, 3, 4, 4, 3] 是对称的。
1
/ \
2 2
/ \ / \
3 4 4 3

但是下面这个 [1, 2, 2, null, 3, null, 3] 则不是镜像对称的:
1
/ \
2 2
\ \
3 3

示例 1:
输入:root = [1, 2, 2, 3, 4, 4, 3]
输出:true

示例 2:
输入:root = [1, 2, 2, null, 3, null, 3]
输出:false

方案(递归)

  1. /**
  2. * Definition for a binary tree node.
  3. * struct TreeNode {
  4. * int val;
  5. * TreeNode *left;
  6. * TreeNode *right;
  7. * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
  8. * };
  9. */
  10. class Solution {
  11. public:
  12. bool isSymmetric(TreeNode* root) {
  13. if (root == NULL) {
  14. return true;
  15. }
  16. return isMirror(root->left, root->right);
  17. }
  18. bool isMirror(TreeNode* l, TreeNode* r) {
  19. if (l == NULL && r == NULL) return true;
  20. if (l == NULL || r == NULL) return false;
  21. if (l->val != r->val) return false;
  22. return isMirror(l->left, r->right) && isMirror(l->right, r->left);
  23. }
  24. };