Symmetric Tree
Problem
Given the root
of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).
Solution Approach
Expected Time complexity:
Click - to see solution code
- C++
class Solution {
public:
bool traversal(TreeNode* p, TreeNode* q) {
if (!p && !q) return true;
if ((!p && q) || (p && !q)) return false;
if (p->val != q->val) return false;
return (traversal(p->right, q->left) & traversal(p->left, q->right));
}
bool isSymmetric(TreeNode* root) {
return traversal(root->left, root->right);
}
};