题目描述:
请实现一个函数,用来判断一棵二叉树是不是对称的。如果一棵二叉树和它的镜像一样,那么它是对称的。
例如,二叉树 [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
限制:
0 <= 节点个数 <= 1000
作者:Krahets
链接:https://leetcode-cn.com/leetbook/read/illustration-of-algorithm/5d412v/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
解答:
/**
* 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(nullptr == root)
return true;
return recur(root->left, root->right);
}
private:
bool recur(TreeNode* L, TreeNode* R){
if(nullptr == L && nullptr == R)
return true;
if(nullptr == L || nullptr == R || L->val != R->val)
return false;
return recur(L->left, R->right) && recur(L->right, R->left);
}
};
运行结果:
Notes:
深度优先搜索&递归
&spm=1001.2101.3001.5002&articleId=122406967&d=1&t=3&u=7330b8ce33254063a0c2bc4f1b8aafa8)
2037

被折叠的 条评论
为什么被折叠?



