We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).
Example 1:
Input: root = [1,2,2,3,4,4,3] Output: true
Example 2:
Input: root = [1,2,2,null,3,null,3] Output: false
Constraints:
Follow up: Could you solve it both recursively and iteratively?
解法一: 递归。比较左右子树。代码如下:
/** * Definition for a binary tree node. * 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) {} * }; */ class Solution { public: bool check(TreeNode* left, TreeNode* right) { if (left && !right) return false; if (right && !left) return false; if (!left && !right) return true; if (left->val == right->val) { return check(left->left, right->right) && check(left->right, right->left); } return false; } bool isSymmetric(TreeNode* root) { if (!root) return true; return check(root->left, root->right); } };
解法二: 迭代法。根据官方题解,一次队列里放两个对应位置的结点。代码如下:
/** * Definition for a binary tree node. * 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) {} * }; */ class Solution { public: bool isSymmetric(TreeNode* root) { if (!root) 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 && !right) continue; if (!left || !right || (left->val != right->val)) { return false; } q.push(left->left); q.push(right->right); q.push(left->right); q.push(right->left); } return true; } };
The text was updated successfully, but these errors were encountered:
No branches or pull requests
Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).
Example 1:

Example 2:

Constraints:
Follow up: Could you solve it both recursively and iteratively?
解法一:
递归。比较左右子树。代码如下:
解法二:
迭代法。根据官方题解,一次队列里放两个对应位置的结点。代码如下:
The text was updated successfully, but these errors were encountered: