递归
- 思路:
- 克隆这棵树,递归比较左右子树互为镜像;
- 终止条件为:
- 都为nullptr,则返回 true;
- 有一个为 nullptr,则返回 false;(形状不一致)
- 形状一致情况下,值要相等、原左子树与镜像右子树、原右子树与镜像左子树也应该互为镜像递归;
/**
* 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* root) {
return check(root, root);
}
private:
bool check(TreeNode* o, TreeNode* m) {
if ((o == nullptr) && (m == nullptr)) {
return true;
} else if ((o == nullptr) || (m == nullptr)) {
return false;
}
return (o->val == m->val) && check(o->left, m->right) && check(o->right, m->left);
}
};