给你一个二叉树的根节点 root
, 检查它是否轴对称。
示例 1:
输入:root = [1,2,2,3,4,4,3] 输出:true
示例 2:
输入:root = [1,2,2,null,3,null,3] 输出:false
- #include
- using namespace std;
-
- //定义二叉树结构体
- 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) {}
- };
-
- /*
- * 定义一个函数传入两个指向根节点的指针p,q
- * 当两个指针指向结点的值相同时递归p的左子树和q的右子树,
- * 递归p的右子树和q的左子树,保证对称性
- */
- bool check(TreeNode* p, TreeNode* q) {
- if (!p && !q) return true;
- if (!p || !q) return false;
- return p->val == q->val && check(p->left, q->right) && check(p->right, q->left);
- }
-
- bool isSymmetric(TreeNode* root) {
- return check(root, root);
- }
-
- int main() {
- TreeNode* r1 = new TreeNode(1);
- TreeNode* r2 = new TreeNode(2);
- TreeNode* r3 = new TreeNode(2);
- TreeNode* r4 = new TreeNode(3);
- TreeNode* r5 = new TreeNode(4);
- TreeNode* r6 = new TreeNode(4);
- TreeNode* r7 = new TreeNode(3);
- r1->left = r2;
- r1->right = r3;
- r2->left = r4;
- r2->right = r5;
- r3->left = r6;
- r3->right = r7;
- r4->left = nullptr;
- r4->right = nullptr;
- r5->left = nullptr;
- r5->right = nullptr;
- r6->left = nullptr;
- r6->right = nullptr;
- r7->left = nullptr;
- r7->right = nullptr;
-
- TreeNode* root = r1;
- bool ans = isSymmetric(root);
- cout << boolalpha << ans << endl;
-
- delete r1, r2, r3, r4, r5, r6, r7;
- return 0;
- }
对称二叉树问题,定义一个函数传入两个指向根节点的指针p,q,当两个指针指向结点的值相同时递归p的左子树和q的右子树,递归p的右子树和q的左子树,保证对称性。