题目分析:[[EVD]] - 剑指 Offer 28. 对称的二叉树
https://leetcode-cn.com/problems/dui-cheng-de-er-cha-shu-lcof/
简单描述:
- 判断一棵二叉树是不是对称的
限制🚫
- 0 <= 节点个数 <= 1000
- 空树是对称的
示例:
1
/ \
2 2
/ \ / \
3 4 4 3
输入:root = [1,2,2,3,4,4,3]
输出:true1
/ \
2 2
\ \
3 3
输入:root = [1,2,2,null,3,null,3]
输出:false
解题思路:
思路:
- #DFS #BFS
- 递归实现,左右子树深搜方向呈镜像
效率:
- 时间复杂度
- 空间复杂度
代码:
class Solution
{
private:
bool isMirror(TreeNode *a, TreeNode *b)
{
if (!a && !b) return true;
if (!a || !b) return false;
return a->val == b->val && isMirror(a->left, b->right) && isMirror(a->right, b->left);
}
public:
bool isSymmetric(TreeNode *root)
{
return !root || isMirror(root->left, root->right);
}
};