题目描述
题目链接:101. Symmetric Tree
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
例子
例子 1
Input:
[1,2,2,3,4,4,3]
Output:true
例子 2
Input:
[1,2,2,null,3,null,3]
Output:false
解题思路
利用递归可以比较方便求解,只需要判断根节点的左右两棵子树left
和 right
是否完全对称,判断方法如下:
- 两子树的根节点都为空,返回
true
- 其中一子树的根节点为空,返回
false
- 两根节点的值不同,返回
false
- 对
left->left, right->right
和left->right, right->left
做同样判断
代码如下:
1 | class Solution { |
- 时间复杂度: O(n)
- 空间复杂度: O(h)
GitHub 代码同步地址: 101.SymmetricTree.cpp
其他题目:
GitHub: Leetcode-C++-Solution
博客: Leetcode-Solutions