"""Blind 75, Tree section (14 problems, including the three trie problems)."""
from collections import deque
from typing import List, Optional

from .structures import TreeNode


def max_depth(root: Optional[TreeNode]) -> int:
    """LC 104. Depth = 1 + the deeper subtree."""
    return 0 if root is None else 1 + max(max_depth(root.left), max_depth(root.right))


def is_same_tree(p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
    """LC 100. Both empty, or same value and both subtrees match."""
    if p is None or q is None:
        return p is q
    return p.val == q.val and is_same_tree(p.left, q.left) and is_same_tree(p.right, q.right)


def invert_tree(root: Optional[TreeNode]) -> Optional[TreeNode]:
    """LC 226. Swap children at every node."""
    if root:
        root.left, root.right = invert_tree(root.right), invert_tree(root.left)
    return root


def max_path_sum(root: TreeNode) -> int:
    """LC 124. Each node returns its best one-sided path upward; the answer may bend through the node."""
    best = root.val

    def gain(node: Optional[TreeNode]) -> int:
        nonlocal best
        if node is None:
            return 0
        left = max(gain(node.left), 0)
        right = max(gain(node.right), 0)
        best = max(best, node.val + left + right)
        return node.val + max(left, right)

    gain(root)
    return best


def level_order(root: Optional[TreeNode]) -> List[List[int]]:
    """LC 102. BFS; process the queue one level at a time using its current length."""
    out: List[List[int]] = []
    queue = deque([root] if root else [])
    while queue:
        level = []
        for _ in range(len(queue)):
            node = queue.popleft()
            level.append(node.val)
            queue.extend(child for child in (node.left, node.right) if child)
        out.append(level)
    return out


class Codec:
    """LC 297. Preorder with explicit null markers is enough to rebuild the exact tree."""

    def serialize(self, root: Optional[TreeNode]) -> str:
        out: List[str] = []

        def walk(node: Optional[TreeNode]) -> None:
            if node is None:
                out.append("#")
                return
            out.append(str(node.val))
            walk(node.left)
            walk(node.right)

        walk(root)
        return ",".join(out)

    def deserialize(self, data: str) -> Optional[TreeNode]:
        tokens = iter(data.split(","))

        def build() -> Optional[TreeNode]:
            tok = next(tokens)
            if tok == "#":
                return None
            node = TreeNode(int(tok))
            node.left = build()
            node.right = build()
            return node

        return build()


def is_subtree(root: Optional[TreeNode], sub: Optional[TreeNode]) -> bool:
    """LC 572. At every node of root, check is_same_tree against sub. O(m*n), fine for interviews."""
    if sub is None:
        return True
    if root is None:
        return False
    return is_same_tree(root, sub) or is_subtree(root.left, sub) or is_subtree(root.right, sub)


def build_tree_pre_in(preorder: List[int], inorder: List[int]) -> Optional[TreeNode]:
    """LC 105. Preorder's next value is the root; its inorder position splits left and right sizes."""
    index = {v: i for i, v in enumerate(inorder)}
    pre = iter(preorder)

    def build(lo: int, hi: int) -> Optional[TreeNode]:
        if lo > hi:
            return None
        val = next(pre)
        node = TreeNode(val)
        node.left = build(lo, index[val] - 1)
        node.right = build(index[val] + 1, hi)
        return node

    return build(0, len(inorder) - 1)


def is_valid_bst(root: Optional[TreeNode]) -> bool:
    """LC 98. Pass down an open (low, high) range; every node must sit strictly inside it."""
    def ok(node: Optional[TreeNode], low: float, high: float) -> bool:
        if node is None:
            return True
        return low < node.val < high and ok(node.left, low, node.val) and ok(node.right, node.val, high)

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


def kth_smallest(root: TreeNode, k: int) -> int:
    """LC 230. Inorder traversal of a BST is sorted; stop at the k-th node visited."""
    stack: List[TreeNode] = []
    node: Optional[TreeNode] = root
    while True:
        while node:
            stack.append(node)
            node = node.left
        node = stack.pop()
        k -= 1
        if k == 0:
            return node.val
        node = node.right


def lowest_common_ancestor(root: TreeNode, p: TreeNode, q: TreeNode) -> TreeNode:
    """LC 235. In a BST, walk down until p and q fall on different sides (or one equals the node)."""
    node = root
    while True:
        if p.val < node.val and q.val < node.val:
            node = node.left
        elif p.val > node.val and q.val > node.val:
            node = node.right
        else:
            return node


class Trie:
    """LC 208. Nested dicts; a special key marks the end of a complete word."""

    END = "$"

    def __init__(self) -> None:
        self.root: dict = {}

    def insert(self, word: str) -> None:
        node = self.root
        for ch in word:
            node = node.setdefault(ch, {})
        node[self.END] = True

    def _walk(self, prefix: str):
        node = self.root
        for ch in prefix:
            if ch not in node:
                return None
            node = node[ch]
        return node

    def search(self, word: str) -> bool:
        node = self._walk(word)
        return node is not None and self.END in node

    def startsWith(self, prefix: str) -> bool:  # noqa: N802 (LeetCode's method name)
        return self._walk(prefix) is not None


class WordDictionary:
    """LC 211. A trie; on '.', try every child (DFS)."""

    def __init__(self) -> None:
        self.root: dict = {}

    def addWord(self, word: str) -> None:  # noqa: N802
        node = self.root
        for ch in word:
            node = node.setdefault(ch, {})
        node["$"] = True

    def search(self, word: str) -> bool:
        def dfs(node: dict, i: int) -> bool:
            if i == len(word):
                return "$" in node
            ch = word[i]
            if ch == ".":
                return any(dfs(child, i + 1) for key, child in node.items() if key != "$")
            return ch in node and dfs(node[ch], i + 1)

        return dfs(self.root, 0)


def find_words(board: List[List[str]], words: List[str]) -> List[str]:
    """LC 212. Put all words in one trie and DFS the board once; prune trie branches once a word is found."""
    root: dict = {}
    for w in words:
        node = root
        for ch in w:
            node = node.setdefault(ch, {})
        node["$"] = w
    rows, cols = len(board), len(board[0])
    found: List[str] = []

    def dfs(r: int, c: int, parent: dict) -> None:
        ch = board[r][c]
        node = parent[ch]
        if "$" in node:
            found.append(node.pop("$"))
        board[r][c] = "#"
        for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
            if 0 <= nr < rows and 0 <= nc < cols and board[nr][nc] in node:
                dfs(nr, nc, node)
        board[r][c] = ch
        if not node:
            parent.pop(ch)

    for r in range(rows):
        for c in range(cols):
            if board[r][c] in root:
                dfs(r, c, root)
    return found
