二叉树]leetcode101:对称二叉树(easy)"/>
[二叉树]leetcode101:对称二叉树(easy)
题目:
题解1:递归法
class Solution {
public:bool isSymmetric(TreeNode* root) {//if(!root||(!root->left&&!root->right))return true;return check(root->left,root->right);}bool check(TreeNode* p,TreeNode* q){if(!p&&!q)return true;if((!p&&q)||(p&&!q))return false;if(p->val!=q->val)return false;return check(p->left,q->right)&&check(p->right,q->left);}
};
题解2:利用层序遍历迭代法解题
class Solution {
public://解法2:迭代法,利用层序遍历比较左右子树的节点bool isSymmetric(TreeNode* root){if(root==nullptr)return true;queue<TreeNode*> q;q.push(root->left);q.push(root->right);while(!q.empty()){TreeNode *left=q.front();q.pop();TreeNode *right=q.front();q.pop();if(left==nullptr&&right==nullptr)//左右节点皆为空continue;if(left==nullptr||right==nullptr)//左右节点有一个为空return false;if(left->val!=right->val)return false;//节点值不等q.push(left->left);q.push(right->right);q.push(right->left);q.push(left->right);}return true;}
};
更多推荐
[二叉树]leetcode101:对称二叉树(easy)
发布评论