101. Symmetric Binary Tree
-
link
leetcode
-
solution:
At first glance, this question is quite simple, but the result is a bit confusing because the writing is not clear.
Finally, think about the symmetry of a tree? Wouldn't it be split into two trees? How can two trees be compared symmetrically? You can use a queue!
One throws the left child in, and the other throws the right child in, taking the head every time. Isn't it more symmetrical? Need to pay attention to these points:
- Throw roots twice the first time
- When throwing left child, right child, there is no need to judge whether it is NULL or not. It is unified to judge these things by judging before throwing.
- Both are NULL, no problem!
- Only one is NULL, I'm sorry, please rest.
- Is the value different? Bye bye!
-
code
class Solution {
public:
bool isSymmetric(TreeNode* root) {
queue<TreeNode*> q;
q.push(root);
q.push(root);
while (!q.empty())
{
auto t1 = q.front();
q.pop();
auto t2 = q.front();
q.pop();
if (!t1 && !t2) continue;
if (!t1 || !t2)
return false;
if (t1->val != t2->val)
return false;//帅啊
q.push(t1->left);
q.push(t2->right);
q.push(t1->right);
q.push(t2->left);
}
return true;
}
};