/**
* 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) {
function<bool(TreeNode*, TreeNode*)> isSameTree = [&](TreeNode* p, TreeNode* q) -> bool {
if(!p && !q) return true;
if(!p || !q) return false;
if(p->val != q->val) return false;
return isSameTree(p->left, q->right) && isSameTree(p->right, q->left);
};
return isSameTree(root->left, root->right);
}
};Time Complexity: O(n), where n is the number of nodes, since we compare each pair of nodes at most once.
Space Complexity: O(h) for the recursion stack, where h is the height of the tree (O(log n) for a balanced tree, O(n) for a skewed tree).