2023每日刷题(十九)
Leetcode---101.对称二叉树

利用Leetcode101.对称二叉树的思想的实现代码
c
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
bool isSameTree(struct TreeNode* p, struct TreeNode* q) {
if(p == NULL && q == NULL) {
return true;
}
if((!p && q) || (p && !q)) {
return false;
}
if(p->val != q->val) {
return false;
}
if(isSameTree(p->left, q->right) && isSameTree(p->right, q->left)) {
return true;
}
return false;
}
bool isSymmetric(struct TreeNode* root) {
return isSameTree(root->left, root->right);
}
运行结果

层次遍历实现代码
cpp
/**
* 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) {
if(root == NULL) {
return true;
}
queue<TreeNode*> qu1, qu2;
TreeNode* p1, *p2;
qu1.push(root->left);
qu2.push(root->right);
while(!qu1.empty() && !qu2.empty()) {
p1 = qu1.front();
qu1.pop();
p2 = qu2.front();
qu2.pop();
if((p1 && !p2) || (!p1 && p2)) {
return false;
}
if(p1 != NULL && p2 != NULL) {
if(p1->val != p2->val) {
return false;
}
qu1.push(p1->left);
qu1.push(p1->right);
qu2.push(p2->right);
qu2.push(p2->left);
}
}
return true;
}
};
运行结果

之后我会持续更新,如果喜欢我的文章,请记得一键三连哦,点赞关注收藏,你的每一个赞每一份关注每一次收藏都将是我前进路上的无限动力 !!!↖(▔▽▔)↗感谢支持!