Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).
For example:
1
/ \
2 2
/ \ / \
3 4 4 3
The above binary tree is symmetric.
However, the following binary tree is not:
1
/ \
2 2
\ \
3 3
None
, return True
. If only one is None
, return False
.We’ll implement the recursive approach here for simplicity.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def isSymmetric(root: TreeNode) -> bool:
def isMirror(left: TreeNode, right: TreeNode) -> bool:
if left is None and right is None:
return True
if left is None or right is None:
return False
return (left.val == right.val and
isMirror(left.left, right.right) and
isMirror(left.right, right.left))
return isMirror(root.left, root.right) if root else True
# Example Usage:
# root = TreeNode(1)
# root.left = TreeNode(2)
# root.right = TreeNode(2)
# root.left.left = TreeNode(3)
# root.left.right = TreeNode(4)
# root.right.left = TreeNode(4)
# root.right.right = TreeNode(3)
# print(isSymmetric(root)) # Output: True
Time Complexity: O(n), where n
is the number of nodes in the tree. Each node is visited exactly once.
Space Complexity: O(h), where h
is the height of the tree. This is the space used by the recursion stack. In the worst case (skewed tree), the height h
could be n
.
This solution efficiently checks whether a binary tree is symmetric by leveraging a recursive helper function to compare the left and right subtrees for mirror properties.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?