class TreeNode {
constructor(val = 0, left = null, right = null) {
this.val = val;
this.left = left;
this.right = right;
}
}
function isSymmetricTrees(t1, t2) {
if (!t1 && !t2) return true;
if (!t1 || !t2) return false;
if (t1.val !== t2.val) return false;
return isSymmetricTrees(t1.left, t2.right) && isSymmetricTrees(t1.right, t2.left);
}
// Build Tree1
const tree1 = new TreeNode(1,
new TreeNode(2, new TreeNode(4), null),
new TreeNode(3, null, new TreeNode(5))
);
// Build Tree2
const tree2 = new TreeNode(1,
new TreeNode(3, new TreeNode(5), null),
new TreeNode(2, null, new TreeNode(4))
);
console.log(isSymmetricTrees(tree1, tree2) ? "Trees are symmetric" : "Trees are not symmetric");if (!t1 && !t2) return true;
both nodes null means symmetry at this branch
if (!t1 || !t2) return false;
one node null and other not means asymmetry
if (t1.val !== t2.val) return false;
node values must match for symmetry
return isSymmetricTrees(t1.left, t2.right) && isSymmetricTrees(t1.right, t2.left);
recursively check mirror children pairs