Contact
Back to Home

In a programming language you are proficient in, how would you code a binary tree inversion?

Featured Answer

Question Analysis

The question is asking you to demonstrate your ability to manipulate data structures, specifically a binary tree, using a programming language you are proficient in. Inverting a binary tree means swapping the left and right children of all nodes in the tree. This is a common problem that tests your understanding of tree traversal algorithms and recursive programming techniques.

Answer

Here is how you can invert a binary tree using Python, which is a commonly used programming language for coding interviews:

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

def invertTree(node):
    if node is None:
        return None

    # Swap the left and right children
    node.left, node.right = node.right, node.left

    # Recursively invert the left subtree
    invertTree(node.left)

    # Recursively invert the right subtree
    invertTree(node.right)

    return node

Key Points:

  • Recursive Approach: The function invertTree recursively inverts the binary tree. If the given node is None, it returns None, which acts as the base case for recursion.
  • Swapping Children: At each node, it swaps the left and right children.
  • Complexity: The time complexity of this function is O(n), where n is the number of nodes in the tree, as each node is visited once. The space complexity is O(h) for the recursion stack, where h is the height of the tree.

This solution efficiently inverts a binary tree using a simple recursive approach, demonstrating a solid understanding of tree data structures and recursive programming.