Imagine you want to verify if a decorative tree in your garden is perfectly symmetrical, like a mirror image on both sides.
Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center). Return true if the tree is symmetric, and false otherwise.
The number of nodes in the tree is in the range [1, 10^5].Node values are integers and can be positive, negative, or zero.
Edge cases: Empty tree (null root) → trueSingle node tree → trueTree with only left children → false
def isSymmetric(root: Optional[TreeNode]) -> bool:public boolean isSymmetric(TreeNode root)bool isSymmetric(TreeNode* root)function isSymmetric(root)
def isSymmetric(root):
# Write your solution here
pass
class Solution {
public boolean isSymmetric(TreeNode root) {
// Write your solution here
return false;
}
}
#include <vector>
using namespace std;
bool isSymmetric(TreeNode* root) {
// Write your solution here
return false;
}
function isSymmetric(root) {
// Write your solution here
}
Common Bugs to Avoid
Wrong: falseReturning false for empty tree (null root) instead of true.✅ Add a base case: if root is null, return true immediately.
Wrong: trueNot checking for null subtree mismatches, causing false positives when one subtree is null and the other is not.✅ Before comparing node values, check if both nodes are null or both non-null; return false if mismatch.
Wrong: falseMixing up left and right pointers in recursive mirror calls.✅ In isMirror, call isMirror(t1.left, t2.right) and isMirror(t1.right, t2.left), not t2.left with t1.left.
Wrong: trueGreedy approach checking only root children without full recursion.✅ Recursively check all subtree pairs for mirror symmetry, not just immediate children.
Wrong: TLEUsing exponential or repeated subtree traversals instead of O(n) DFS.✅ Implement a single DFS traversal with early exit on mismatch to achieve O(n) time complexity.