Tap here to switch tabs
Problem
Ask
Submissions

Problem: Recover a Tree From Preorder Traversal

hard
40 min
Understand how to reconstruct a binary tree given its preorder traversal string where node depth is indicated by dashes. Learn to apply depth-first search techniques and handle tree node relationships effectively to rebuild the original tree structure.

Statement

We perform a preorder depth-first traversal on a binary tree starting from its root.

  • For each node, we first write D dashes, where D is the depth of the node in the tree, followed by the node’s integer value.

  • The root node has depth 0.

  • If a node is at depth D, its children (if any) will appear at depth D + 1.

  • If a node has only one child, it will always be the left child.

You are given the string representation of this traversal. Your task is to reconstruct the original binary tree and return its root.

Constraints:

  • The number of nodes in the original binary tree lies within the range [1,500][1, 500].

  • 11 \leq node.data 103\leq 10^3

Tap here to switch tabs
Problem
Ask
Submissions

Problem: Recover a Tree From Preorder Traversal

hard
40 min
Understand how to reconstruct a binary tree given its preorder traversal string where node depth is indicated by dashes. Learn to apply depth-first search techniques and handle tree node relationships effectively to rebuild the original tree structure.

Statement

We perform a preorder depth-first traversal on a binary tree starting from its root.

  • For each node, we first write D dashes, where D is the depth of the node in the tree, followed by the node’s integer value.

  • The root node has depth 0.

  • If a node is at depth D, its children (if any) will appear at depth D + 1.

  • If a node has only one child, it will always be the left child.

You are given the string representation of this traversal. Your task is to reconstruct the original binary tree and return its root.

Constraints:

  • The number of nodes in the original binary tree lies within the range [1,500][1, 500].

  • 11 \leq node.data 103\leq 10^3