47 lines
1.5 KiB
C++
47 lines
1.5 KiB
C++
// https://leetcode.com/problems/symmetric-tree/submissions/1292981419/
|
|
|
|
/**
|
|
* 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) {}
|
|
};
|
|
|
|
/**
|
|
* Method:
|
|
* - Reverse the right-hand side
|
|
* - Check whether the left and right are now equal via a pre-order traversal.
|
|
* - Time: O(n)
|
|
* - Space: O(n).
|
|
*
|
|
* On my first time, I didn't see that the problem could be solved directly by comparing the trees recursively;
|
|
* doing this would still be O(n) time and space, but avoid having to invert the right tree for no other reason.
|
|
*/
|
|
class Solution {
|
|
public:
|
|
bool isSymmetric(TreeNode* root) {
|
|
reverseBinaryTree(root->right);
|
|
return treesAreEqual(root->left, root->right);
|
|
}
|
|
|
|
void reverseBinaryTree(TreeNode* root) {
|
|
if (root == nullptr) return;
|
|
TreeNode* temp = root->left;
|
|
root->left = root->right;
|
|
root->right = temp;
|
|
reverseBinaryTree(root->left);
|
|
reverseBinaryTree(root->right);
|
|
}
|
|
|
|
bool treesAreEqual(TreeNode* left, TreeNode* right) {
|
|
if (left == nullptr) return right == nullptr;
|
|
if (right == nullptr) return left == nullptr;
|
|
return (left->val != right->val) && treesAreEqual(left->left, right->left) && treesAreEqual(left->right, right->right);
|
|
}
|
|
};
|