力扣101

tech2025-08-11  16

递归迭代

递归

class Solution { public: bool isSymmetric(TreeNode* root) { return check(root, root); } bool check(TreeNode* tree1, TreeNode* tree2) { if(!tree1 && !tree2) return true; if(!tree1 || !tree2) return false; return tree1->val == tree2->val && check(tree1->left, tree2->right) && check(tree1->right, tree2->left); } };

迭代

和之前对二叉树的处理类似,可以通过队列的方式处理递归的过程。在首次创建队列时将root入队2次即可,每次提取两个结点并比较它们的值(队列中每两个连续的结点应该是相等的,而且它们的子树互为镜像),然后将两个结点的左右子结点按相反的顺序插入队列中。当队列为空时,或者我们检测到树不对称(即从队列中取出两个不相等的连续结点)时,该算法结束。

class Solution{ public: bool isSymmetric(TreeNode* root){//使用迭代的方法 return check(root, root); } bool check(TreeNode* t1, TreeNode* t2) { queue<TreeNode*> q; q.push(t1); q.push(t2); while(!q.empty()){ auto l = q.front(); q.pop(); auto r = q.front(); q.pop(); if(!l && !r) continue; if(!l|| !r ||(l->val != r->val)) return false; q.push(l->left); q.push(r->right); q.push(l->right); q.push(r->left); } return true; } };

最新回复(0)