28.对称的二叉树 (Easy)*
题目描述*
请实现一个函数,用来判断一棵二叉树是不是对称的。如果一棵二叉树和它的镜像一样,那么它是对称的。
示例*
例如,二叉树 [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
限制*
0 <= 节点个数 <= 1000
代码*
递归、栈、bfs。
class Solution {
public:
bool isSymmetric(TreeNode* root) {
if(root == nullptr) {
return true;
}
return helper(root->left, root->right);
}
bool helper(TreeNode *left, TreeNode *right) {
if(left == nullptr && right != nullptr || left != nullptr && right == nullptr) {
return false;
}
if(left != nullptr && right != nullptr) {
if(left->val != right->val) {
return false;
}
return helper(left->left, right->right) && helper(left->right, right->left);
}
return true;
}
};
class Solution {
public:
bool isSymmetric(TreeNode* root) {
if(root == nullptr) {
return true;
}
stack<TreeNode*> lStack;
stack<TreeNode*> rStack;
TreeNode *curLeft = root->left;
TreeNode *curRight = root->right;
while(curLeft != nullptr || !lStack.empty() || curRight != nullptr || !rStack.empty()) {
while(curLeft != nullptr) {
lStack.push(curLeft);
curLeft = curLeft->left;
}
while(curRight != nullptr) {
rStack.push(curRight);
curRight = curRight->right;
}
if(lStack.size() != rStack.size()) {
return false;
}
curLeft = lStack.top();
lStack.pop();
curRight = rStack.top();
rStack.pop();
if(curRight->val != curLeft->val) {
return false;
}
curLeft = curLeft->right;
curRight = curRight->left;
}
return true;
}
};
class Solution {
public:
bool isSymmetric(TreeNode* root) {
if(root == nullptr) {
return true;
}
queue<TreeNode*> helpQueue;
helpQueue.push(root);
helpQueue.push(root);
TreeNode *cur1 = root, *cur2 = root;
while(!helpQueue.empty()) {
cur1 = helpQueue.front();
helpQueue.pop();
cur2 = helpQueue.front();
helpQueue.pop();
if(cur1 == nullptr && cur2 == nullptr) {
continue;
}
if(cur1 == nullptr || cur2 == nullptr) {
return false;
}
if(cur1->val != cur2->val) {
return false;
}else {
helpQueue.push(cur1->left);
helpQueue.push(cur2->right);
helpQueue.push(cur1->right);
helpQueue.push(cur2->left);
}
}
return true;
}
};
最后更新: July 23, 2022