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 itsroot.
The number of nodes in the original tree is in the range [1, 1000].
1 <= Node.val <= 10⁹
Test Cases
1 2 3 4 5 6 7 8
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right classSolution: defrecoverFromPreorder(self, traversal: str) -> Optional[TreeNode]:
import os import sys sys.path.append(os.path.dirname(os.path.dirname(__file__))) from _utils.binary_tree import print_tree from solution import Solution
# Definition for a binary tree node. classTreeNode: def__init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right
classSolution: defrecoverFromPreorder(self, traversal: str) -> Optional[TreeNode]: stack = [] # path from root to current node for level, val inself.tokenize(traversal): whilelen(stack) > level: stack.pop()
node = TreeNode(val) if stack: parent = stack[-1] if parent.left isNone: parent.left = node else: parent.right = node
stack.append(node)
return stack[0]
deftokenize(self, traversal: str) -> Iterable[tuple[int, int]]: level = 0 for part in traversal.split('-'): ifnot part: level += 1 else: yield level, int(part) level = 1