-
解题思路
- 检查一个二叉树是否轴对称,其实和根结点无关,而是和其左右子树有关。
- 左子树头等于右子树头,然后递归调用,「左子树的右儿子」要等于「右子树的左儿子」并且「左子树的左儿子」要等于「右子树的左儿子」。
-
代码
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: bool isSymmetric(TreeNode* head1, TreeNode *head2) { if (head1 == nullptr && head2 == nullptr) { return true; } if (head1 == nullptr) { return false; } if (head2 == nullptr) { return false; } if (head1->val != head2->val) { return false; } return isSymmetric(head1->left, head2->right) && isSymmetric(head1->right, head2->left); } bool isSymmetric(TreeNode* root) { return isSymmetric(root->left, root->right); } };