We run a preorder depth-first search (DFS) on the root of a binary tree.At each node in this traversal, we output D dashes (where D is the depth of this node), then we output the value of this node. If the depth of a node is D, the depth of its immediate child is D + 1. The depth of the root node is 0.If a node has only one child, that child is guaranteed to be the left child.Given the output traversal of this traversal, recover the tree and return its root.
from leetcode_py import TreeNodeclass Solution: # Time: O(n) over the traversal length # Space: O(depth) for the node stack def recover_from_preorder(self, traversal: str) -> TreeNode[int] | None: i = 0 n = len(traversal) stack: list[TreeNode[int]] = [] while i < n: depth = 0 while i < n and traversal[i] == "-": depth += 1 i += 1 value = 0 while i < n and traversal[i].isdigit(): value = value * 10 + int(traversal[i]) i += 1 node: TreeNode[int] = TreeNode(value) while len(stack) > depth: stack.pop() if stack: if stack[-1].left is None: stack[-1].left = node else: stack[-1].right = node stack.append(node) return stack[0]