题目:
Given the root
of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).
Example 1:
Input: root = [1,2,2,3,4,4,3] Output: true
Example 2:
Input: root = [1,2,2,null,3,null,3] Output: false
Constraints:
- The number of nodes in the tree is in the range
[1, 1000]
. -100 <= Node.val <= 100
思路1:
判断一棵树是不是镜像对称。先用bfs里比较笨但是好理解的思路来了一遍。在按层遍历的基础上,增加一个存Treenode*的vector,把当前层的所有子都存进去,包括空子,然后将这个vector对称比较。比较分五种情况,假设左边的node为 com[i], 右边的node为com[j]:一是左右都为空,则对称;二是左空又不空,不对称;三是左不空右空,不对称;四是左右都不空但值不相等,不对称;五是左右都不空且值相等,则对称。只要是不对称的情况,直接返回false即可。这种多一个vector的解法比较好理解,就是多占空间复杂度。
代码1:
/**
* 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) {
queue<TreeNode*> q;
q.push(root);
while(q.size()) {
int len = q.size();
vector<TreeNode*> com;
for (int i = 0; i < len; i++) {
auto tmp = q.front();
q.pop();
com.push_back(tmp->left);
com.push_back(tmp->right);
if (tmp->left)
q.push(tmp->left);
if (tmp->right)
q.push(tmp->right);
}
for (int i = 0, j = com.size() - 1; i < com.size() / 2; i++, j--) {
if (!com[i] && !com[j])
continue;
if (com[i] && com[j] && com[i]->val == com[j]->val)
continue;
return false;
}
}
return true;
}
};
思路2:
dfs写法,我们已知上面讨论了的五种情况,那就是base case。不对称的情况直接返回false;而左右都空的情况下,我们是不需要往下递归的,因此也可以直接返回ture,最后一种左右不为空且值相等的情况,我们才继续递归。我们需要比较的外侧和内侧的子树,即左子的左子要和右子的右子相同,左子的右子和右子的左子相同,之后返回这两者结果的&&即可。
代码2:
/**
* 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 dfs(root->left, root->right);
}
private:
bool dfs(TreeNode* left, TreeNode* right) {
if (!left && !right)
return true;
else if (left && !right)
return false;
else if (!left && right)
return false;
else if (left->val != right->val)
return false;
bool waice = dfs(left->left, right->right);
bool neice = dfs(left->right, right->left);
return waice && neice;
}
};