Symmetric Tree
Given the root of a binary tree, determine whether it looks the same when reflected across its vertical center — in other words, whether the left and right subtrees are mirror images of each other.
Input Format
Implement isSymmetric(root). Inputs below show JavaScript function arguments; there is no stdin parsing.
Trees use level-order arrays with null for missing children. The editor passes nodes with val, left, and right properties; [] becomes null.
Output Format
Return the result described in the statement.
Sample Input and Output
Example 1 · Run Sample
Input
root = [1,2,2,3,4,4,3] Output
true Example 2
Input
root = [1,2,2,null,3,null,3] Output
false Constraints
- 1 <= number of nodes <= 1000
- -100 <= Node.val <= 100
Test Cases (2)
Case 1
Args: [[1,2,2,3,4,4,3]]
Expected: true
Case 2
Args: [[1,2,2,null,3,null,3]]
Expected: false
Topics
Recursive Mirror Check
function isSymmetric(root) {
function isMirror(a, b) {
if (!a && !b) return true;
if (!a || !b || a.val !== b.val) return false;
return isMirror(a.left, b.right) && isMirror(a.right, b.left);
}
return isMirror(root, root);
}Time: O(n) | Space: O(h)
Saved in this browser only. Private to you.