101. Symmetric Tree
Asked at 10Bloomberg55Microsoft49Amazon48Google42Meta38Yandex59VK68LinkedIn62EPAM Systems51Infosys39
Problem
Decide whether a binary tree is a mirror image of itself around its centre.
Example: [1,2,2,3,4,4,3] → true; [1,2,2,null,3,null,3] → false
Constraints: follow-up: both recursively and iteratively.
A tree is symmetric if left and right subtrees are mirrors: mirror(a, b) = a.val == b.val && mirror(a.left, b.right) && mirror(a.right, b.left).
Complexity: O(n).
class Solution:
def isSymmetric(self, root: Optional[TreeNode]) -> bool:
def mirror(a, b):
if not a or not b:
return a is b
return a.val == b.val and mirror(a.left, b.right) and mirror(a.right, b.left)
return mirror(root.left, root.right)
assert Solution().isSymmetric(make_tree([1, 2, 2, 3, 4, 4, 3])) is True
assert Solution().isSymmetric(make_tree([1, 2, 2, None, 3, None, 3])) is False
class Solution {
public boolean isSymmetric(TreeNode root) { return mirror(root.left, root.right); }
private boolean mirror(TreeNode a, TreeNode b) {
if (a == null || b == null) return a == b;
return a.val == b.val && mirror(a.left, b.right) && mirror(a.right, b.left);
}
}
func isSymmetric(root *TreeNode) bool {
var mirror func(a, b *TreeNode) bool
mirror = func(a, b *TreeNode) bool {
if a == nil || b == nil {
return a == b
}
return a.Val == b.Val && mirror(a.Left, b.Right) && mirror(a.Right, b.Left)
}
return mirror(root.Left, root.Right)
}