Algorithmsbinary tree recursion

Binary Tree Recursion — Trust the Subtree Answer

TT
Testlaa Team
May 14, 20261 min read

Recursive tree functions assume children already solved; your job is combine at the current node (sum, max depth, path sums).

Try this in Python

from __future__ import annotations
from dataclasses import dataclass


@dataclass
class TreeNode:
    val: int
    left: TreeNode | None = None
    right: TreeNode | None = None


def sum_tree(root: TreeNode | None) -> int:
    if not root:
        return 0
    return root.val + sum_tree(root.left) + sum_tree(root.right)

r = TreeNode(1, TreeNode(2), TreeNode(3))
print(sum_tree(r))

Key takeaways

  • Base case is usually not root returning neutral (0, 0, True, etc.).
  • Post-order feel appears when you need both subtrees before deciding at root.
  • Draw three-node examples to sanity-check.

Tags:

Tree structuresPythonStudents