题目
请实现一个函数,用来判断一棵二叉树是不是对称的。如果一棵二叉树和它的镜像一样,那么它是对称的。
例如,二叉树 [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
方案(递归)
/*** Definition for a binary tree node.* 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;}return isMirror(root->left, root->right);}bool isMirror(TreeNode* l, TreeNode* r) {if (l == NULL && r == NULL) return true;if (l == NULL || r == NULL) return false;if (l->val != r->val) return false;return isMirror(l->left, r->right) && isMirror(l->right, r->left);}};
- 左子树的左子节点等于右子书的右子节点且左子树的右子节点等于右子树的左子节点即可。
参考链接
https://leetcode-cn.com/leetbook/read/illustrate-lcof/xsrxq1/
https://leetcode-cn.com/leetbook/read/illustrate-lcof/xsrj37/
