educative.io

Optimizing Symmetric Tree

The provided optimal solution has a space complexity of O(n), where n is the number of nodes. If we use dfs, can we reduce this to O(h), where h is the height of the tree? If so, the problem may be better suited for the dfs section.

def is_symmetric(root):

  def dfs(left, right):
    if not left and not right:
      return True
    if not left or not right or left.data != right.data:
      return False
    return dfs(left.left, right.right) and dfs(left.right, right.left)
    
  return dfs(root.left, root.right)

Course: Grokking Coding Interview Patterns in Python - AI-Powered Learning for Developers
Lesson: https://www.educative.io/courses/grokking-coding-interview-patterns-python/solution-symmetric-tree