Leetcode Problem 1028. Recover a Tree From Preorder Traversal
1028. Recover a Tree From Preorder Traversal
Leetcode Solutions
Iterative Stack Solution
Initialize an empty stack to keep track of nodes.
Initialize variables to keep track of the current index in the string, the current depth, and the current node's value.
Iterate through the traversal string.
a. Count the number of dashes to determine the current depth.
b. Parse the next number to determine the node's value.
c. If the stack size is greater than the current depth, pop from the stack until the sizes match.
d. Create a new node with the parsed value.
e. If the stack is not empty, add the new node as a left or right child of the node at the top of the stack.
f. Push the new node onto the stack.
After the loop, the root of the tree will be at the bottom of the stack. Pop all other nodes and return the root.