using System; class TreeNode { public int val; public TreeNode left, right; public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) { this.val = val; this.left = left; this.right = right; } } class Solution { public bool AreSymmetric(TreeNode t1, TreeNode t2) { if (t1 == null && t2 == null) return true; if (t1 == null || t2 == null) return false; if (t1.val != t2.val) return false; return AreSymmetric(t1.left, t2.right) && AreSymmetric(t1.right, t2.left); } } class Program { static void Main() { TreeNode tree1 = new TreeNode(1, new TreeNode(2), new TreeNode(3)); TreeNode tree2 = new TreeNode(1, new TreeNode(3), new TreeNode(2)); Solution sol = new Solution(); Console.WriteLine(sol.AreSymmetric(tree1, tree2)); } }
The function recursively checks if the left subtree of the first tree is symmetric to the right subtree of the second tree and vice versa. Here, tree1 and tree2 are mirror images, so the output is True.
Symmetry between two trees means one tree's left subtree is the mirror image of the other's right subtree, and their node values match accordingly.
public bool AreSymmetric(TreeNode t1, TreeNode t2) { if (t1 == null && t2 == null) return true; if (t1 == null || t2 == null) return false; if (t1.val != t2.val) return false; return AreSymmetric(t1.left, t2.left) && AreSymmetric(t1.right, t2.right); }
The code incorrectly compares the left subtree of one tree with the left subtree of the other, and right with right, instead of comparing left with right and right with left. This causes it to fail for symmetric trees that are mirror images.
public bool AreSymmetric(TreeNode t1, TreeNode t2) { if (t1 == null && t2 == null) return true if (t1 == null || t2 == null) return false; if (t1.val != t2.val) return false; return AreSymmetric(t1.left, t2.right) && AreSymmetric(t1.right, t2.left); }
In C#, each statement must end with a semicolon. The first return statement is missing a semicolon, causing a syntax error.
Each node pair leads to two recursive calls for its children. For 7 nodes, the total calls including null checks sum to 13.
