#1028

Recover a Tree From Preorder Traversal

Hard
StringTreeDepth-First SearchBinary TreeStackDepth-First Search
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses a stack to track nodes and their depths efficiently, allowing us to reconstruct the tree in a single pass through the string. This method is much faster and avoids redundant checks.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize an empty stack to hold nodes.
  2. 2Step 2: Loop through the string, counting dashes to determine the depth of each node and extracting the node value.
  3. 3Step 3: For each node, use the stack to find the correct parent based on depth, linking the node appropriately.
solution.py30 lines
1class TreeNode:
2    def __init__(self, val=0, left=None, right=None):
3        self.val = val
4        self.left = left
5        self.right = right
6
7class Solution:
8    def recoverFromPreorder(self, S: str) -> TreeNode:
9        stack = []
10        i = 0
11        while i < len(S):
12            level = 0
13            while i < len(S) and S[i] == '-':
14                level += 1
15                i += 1
16            val = 0
17            while i < len(S) and S[i].isdigit():
18                val = val * 10 + int(S[i])
19                i += 1
20            node = TreeNode(val)
21            if level == len(stack):
22                if stack:
23                    stack[-1].left = node
24                stack.append(node)
25            else:
26                while level < len(stack):
27                    stack.pop()
28                stack[-1].right = node
29                stack.append(node)
30        return stack[0]

Complexity note: The time complexity is O(n) because we traverse the string once, and the space complexity is O(n) due to the stack storing nodes.

  • 1Understanding the relationship between depth and node placement is crucial for tree reconstruction.
  • 2Using a stack effectively allows us to manage parent-child relationships without excessive searching.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.