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
分析:前面提过二叉树的题目主要都可以用递归和遍历解决。这题也能用递归进行解决。
/** * 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 == nullptr) return true; return judgeSymmetric(root->left, root->right); } private: bool judgeSymmetric(TreeNode *node, TreeNode *mirror) { if(node == nullptr && mirror == nullptr) return true; else if(node != nullptr && mirror != nullptr && node->val == mirror->val) return judgeSymmetric(node->right, mirror->left) && judgeSymmetric(node->left, mirror->right); else return false; } };