ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

【力扣 - 对称二叉树】

2026/9/14 23:15:18 拓冰建站 浏览量
【力扣 - 对称二叉树】

题目描述

给你一个二叉树的根节点 root , 检查它是否轴对称。
在这里插入图片描述
在这里插入图片描述

提示:

树中节点数目在范围 [1, 1000]

-100 <= Node.val <= 100

题解1

/*** Definition for a binary tree node.* struct TreeNode {*     int val;*     struct TreeNode *left;*     struct TreeNode *right;* };*/
// Helper function to check if two trees are symmetric
bool check(struct TreeNode* p, struct TreeNode* q)
{// If both nodes are NULL, they are symmetricif(p == NULL && q == NULL)return true;// If one node is NULL and the other is not, they are not symmetricif(p == NULL || q == NULL)return false;// If the values of the nodes are equal, recursively check their childrenif(p->val == q->val)return check(p->left, q->right) && check(p->right, q->left);elsereturn false;
}// Main function to check if a binary tree is symmetric
bool isSymmetric(struct TreeNode* root){// Call the helper function with the root node to check symmetryreturn check(root, root);
}

题解2

/*** Definition for a binary tree node.* struct TreeNode {*     int val;*     struct TreeNode *left;*     struct TreeNode *right;* };*/
bool isSymmetric(struct TreeNode* root){if (root == NULL) return true; // If the root is NULL, it is symmetricreturn fun(root->left, root->right); // Check symmetry of left and right subtrees
}int fun(struct TreeNode* l_root, struct TreeNode* r_root){if (l_root == NULL && r_root == NULL) return true; // If both nodes are NULL, they are symmetricif (l_root == NULL || r_root == NULL) return false; // If one node is NULL and the other is not, they are not symmetricreturn (l_root->val == r_root->val) && // Check if values of nodes are equalfun(l_root->left, r_root->right) && // Recursively check left of left subtree with right of right subtreefun(l_root->right, r_root->left); // Recursively check right of left subtree with left of right subtree
}