leetcode刷题笔记 101.对称二叉树【简单】
作者:互联网
1、递归
bool helper(TreeNode* lnode, TreeNode* rnode) {
if (lnode == NULL && rnode == NULL)
return true;
else if (lnode == NULL || rnode == NULL)
return false;
else if (lnode->val == rnode->val)
return helper(lnode->left, rnode->right) && helper(lnode->right, rnode->left);
return false;
}
bool isSymmetric(TreeNode* root) {
return helper(root, root);
}
2、迭代(广度优先搜索)
bool isSymmetric(TreeNode* root) {
//广度优先搜索
queue<TreeNode*> q;
TreeNode* lnode = root, * rnode = root;
q.push(lnode);
q.push(rnode);
while (!q.empty()) {
lnode = q.front();
q.pop();
rnode = q.front();
q.pop();
if (lnode->val != rnode->val)
return false;
if (lnode->left != NULL && rnode->right != NULL) {
q.push(lnode->left);
q.push(rnode->right);
}
else if (((lnode->left == NULL) ^ (rnode->right == NULL)) == 1)
return false;
if (lnode->right != NULL && rnode->left != NULL) {
q.push(lnode->right);
q.push(rnode->left);
}
else if (((lnode->right == NULL) ^ (rnode->left == NULL)) == 1)
return false;
}
return true;
}
标签:NULL,return,lnode,rnode,right,二叉树,101,leetcode,left 来源: https://blog.csdn.net/weixin_46477226/article/details/119320878