"""Pattern 10: Tree depth-first search.

Write a recursive helper that returns what the PARENT needs from a subtree
(height, sum, "is valid", best path through me...). Decide whether work
happens before the children (pre-order: pass info down) or after
(post-order: combine info coming up).
"""

from templates.structures import TreeNode


def max_depth(root: TreeNode | None) -> int:
    if root is None:
        return 0
    return 1 + max(max_depth(root.left), max_depth(root.right))


def has_path_sum(root: TreeNode | None, target: int) -> bool:
    """Pre-order: pass the remaining sum down to the leaves."""
    if root is None:
        return False
    remaining = target - root.val
    if root.left is None and root.right is None:
        return remaining == 0
    return has_path_sum(root.left, remaining) or has_path_sum(root.right, remaining)


def path_sums(root: TreeNode | None, target: int) -> list[list[int]]:
    """All root-to-leaf paths summing to target (DFS + backtracking on `path`)."""
    paths: list[list[int]] = []
    path: list[int] = []

    def dfs(node: TreeNode | None, remaining: int) -> None:
        if node is None:
            return
        path.append(node.val)
        remaining -= node.val
        if node.left is None and node.right is None and remaining == 0:
            paths.append(path.copy())
        dfs(node.left, remaining)
        dfs(node.right, remaining)
        path.pop()

    dfs(root, target)
    return paths


def diameter(root: TreeNode | None) -> int:
    """Post-order: each call returns its height and updates a global best."""
    best = 0

    def height(node: TreeNode | None) -> int:
        nonlocal best
        if node is None:
            return 0
        left, right = height(node.left), height(node.right)
        best = max(best, left + right)  # edges on the path through `node`
        return 1 + max(left, right)

    height(root)
    return best


def lowest_common_ancestor(root: TreeNode | None, p: TreeNode, q: TreeNode) -> TreeNode | None:
    if root is None or root is p or root is q:
        return root
    left = lowest_common_ancestor(root.left, p, q)
    right = lowest_common_ancestor(root.right, p, q)
    if left and right:
        return root
    return left or right


def is_valid_bst(root: TreeNode | None) -> bool:
    """Pre-order: pass the allowed (low, high) range down."""

    def check(node: TreeNode | None, low: float, high: float) -> bool:
        if node is None:
            return True
        if not low < node.val < high:
            return False
        return check(node.left, low, node.val) and check(node.right, node.val, high)

    return check(root, float("-inf"), float("inf"))
