本文共 1212 字,大约阅读时间需要 4 分钟。
给定一个二叉树,检查它是否是镜像对称的,即是否关于其中心对称。
1 / \2 2 / \ / \ 3 4 4 3
1 / \2 2 / \ null null / \ 3 3
使用队列来逐层检查树的对称性。将根节点的左、右子节点分别入队。然后,依次取出队列中的节点,比较它们的值及左右、右子节点的位置,确保左右子树对称。
class Solution { bool isSymmetric(TreeNode* root) { if (root == NULL) return true; queue q1, q2; q1.push(root->left); q2.push(root->right); while (!q1.empty() && !q2.empty()) { TreeNode* left = q1.front(); q1.pop(); TreeNode* right = q2.front(); q2.pop(); if (left == NULL && right == NULL) continue; if (left == NULL || right == NULL) return false; if (left->val != right->val) return false; q1.push(left->left); q1.push(left->right); q2.push(right->right); q2.push(right->left); } return true; }} 通过以上优化,内容更具可读性和搜索引擎友好性。
转载地址:http://pfir.baihongyu.com/