Question bank

How can you write a function to check if a binary tree is symmetric?

January 6, 20253 min read
MediumCodingAlgorithm DesignProblem-SolvingData StructuresSoftware EngineerData Scientist
How can you write a function to check if a binary tree is symmetric?

Approach When addressing the question "How can you write a function to check if a binary tree is symmetric?", it is essential to follow a structured framework that demonstrates both your coding skills and your understanding of data structures. Here’s a…

Approach

When addressing the question "How can you write a function to check if a binary tree is symmetric?", it is essential to follow a structured framework that demonstrates both your coding skills and your understanding of data structures. Here’s a breakdown of the thought process:

  1. Understand the Problem:
  • A binary tree is symmetric if its left and right subtrees are mirror images of each other.
  • Identify the properties of a symmetric tree.
  • Choose an Approach:
  • Decide between iterative or recursive methods. Both approaches can effectively solve this problem.
  • Plan the Function:
  • Define the function signature.
  • Outline the steps involved in checking symmetry.
  • Implement the Solution:
  • Write clean, efficient code.
  • Ensure you handle edge cases, such as empty trees.
  • Test the Function:
  • Create test cases to validate your implementation.

Key Points

  • Definitions: Clearly define what a symmetric binary tree is.
  • Approach: Choose between recursive and iterative methods.
  • Function Signature: Clearly define input parameters and return values.
  • Efficiency: Aim for a time complexity of O(n) and a space complexity of O(h), where h is the height of the tree.
  • Edge Cases: Consider scenarios like empty trees or trees with one node.

Standard Response

Here’s a sample answer that incorporates best practices:

class TreeNode:
 def __init__(self, val=0, left=None, right=None):
 self.val = val
 self.left = left
 self.right = right

def is_symmetric(root: TreeNode) -> bool:
 """
 Check if a binary tree is symmetric around its center.
 
 :param root: The root node of the binary tree.
 :return: True if the tree is symmetric, False otherwise.
 """
 if not root:
 return True
 
 def is_mirror(left: TreeNode, right: TreeNode) -> bool:
 if not left and not right:
 return True
 if not left or not right:
 return False
 return (left.val == right.val) and is_mirror(left.right, right.left) and is_mirror(left.left, right.right)
 
 return is_mirror(root.left, root.right)

Explanation:

  • TreeNode Class: A simple class to represent nodes in the binary tree.
  • issymmetric Function: This function checks if the tree is symmetric by utilizing a helper function ismirror.
  • is_mirror Helper Function: This function recursively checks two subtrees for symmetry.

Tips & Variations

Common Mistakes to Avoid:

  • Failure to Handle Edge Cases: Always test for an empty tree or a tree with one node.
  • Inefficient Code: Avoid unnecessary computations and ensure you don't traverse the tree more than once.

Alternative Ways to Answer:

  • Iterative Approach: You can also implement this using a queue for a breadth-first search (BFS) style traversal.
from collections import deque

def is_symmetric_iterative(root: TreeNode) -> bool:
 if not root:
 return True
 
 queue = deque([(root.left, root.right)])
 
 while queue:
 left, right = queue.popleft()
 
 if not left and not right:
 continue
 if not left or not right:
 return False
 if left.val != right.val:
 return False
 
 queue.append((left.left, right.right))
 queue.append((left.right, right.left))
 
 return True

Role-Specific Variations:

  • Technical Roles: Focus on the efficiency of your solution and discuss the time and space complexity.
  • Managerial Roles: Emphasize your ability to lead a team in developing data structure solutions and fostering collaborative problem-solving.
  • Creative Roles: Illustrate your innovative approach to developing algorithms in a way that enhances user experience or application performance.

Follow-Up Questions

  • What are the time and space complexities of your solution?
  • How would you modify your function to handle trees with additional properties, such as balancing?
  • Can you explain how this function could be adapted for a different type of tree structure?

By following this structured approach, job seekers can craft a compelling response that showcases their coding abilities and problem-solving skills, making them stand out in technical interviews

VA

Verve AI Editorial Team

Question Bank