Problem Description
Given a string representing the preorder traversal of a binary tree where each node is represented by D dashes (indicating its depth) followed by the node's value, reconstruct the binary tree. The left child is always visited before the right child, and if a node has only one child, it is guaranteed to be the left child.
Key Insights
- Use the number of dashes to determine the depth of the current node.
- Leverage a stack to maintain the path of nodes from the root to the current node.
- When a node with a smaller depth is encountered, pop nodes from the stack until the correct parent is found.
- Each new node is attached as the left or right child based on whether the left child already exists.
Space and Time Complexity
Time Complexity: O(N) where N is the length of the traversal string (or number of nodes), since each character/node is processed once. Space Complexity: O(N) for the stack holding the path from the root to the deepest node.
Solution
To solve the problem, we iterate through the input string while counting consecutive dashes to identify the node depth and then read the integer value that follows. A stack is used to keep track of nodes corresponding to their depths. For every new node:
- Count the number of consecutive dashes to deduce its depth.
- Parse the integer for the node's value.
- If the current stack length is greater than the current depth, pop from the stack until its length equals the current depth.
- Attach the new node as a left child if the parent does not have one; otherwise, attach it as a right child.
- Push the new node onto the stack. This ensures that the tree is correctly rebuilt following the given preorder traversal.