LeetCode 1028: Recover a Tree From Preorder Traversal Solution
Master LeetCode problem 1028 (Recover a Tree From Preorder Traversal), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
1028. Recover a Tree From Preorder Traversal
Problem Explanation
Explanation
To recover a binary tree from the given preorder traversal string, we can use a stack to keep track of the nodes and their depths. We iterate over the characters in the traversal string, extract the node values and depths, and construct the tree accordingly.
The algorithm involves the following steps:
- Initialize an empty stack to store nodes and their depths.
- Iterate over the traversal string character by character.
- Extract the node value and depth from the current substring.
- Create the node with the extracted value.
- Update the tree structure based on the depth of the current node and the stack.
- Push the node and its depth onto the stack for future reference.
At the end of the process, the root node of the recovered tree will be at the top of the stack.
Time complexity: O(n), where n is the length of the traversal string. Space complexity: O(n), where n is the length of the traversal string.
Solution Code
class Solution {
public TreeNode recoverFromPreorder(String traversal) {
Stack<TreeNode> stack = new Stack<>();
int i = 0;
while (i < traversal.length()) {
int depth = 0;
while (i < traversal.length() && traversal.charAt(i) == '-') {
depth++;
i++;
}
int value = 0;
while (i < traversal.length() && Character.isDigit(traversal.charAt(i))) {
value = value * 10 + (traversal.charAt(i) - '0');
i++;
}
TreeNode node = new TreeNode(value);
while (stack.size() > depth) {
stack.pop();
}
if (!stack.isEmpty()) {
TreeNode parent = stack.peek();
if (parent.left == null) {
parent.left = node;
} else {
parent.right = node;
}
}
stack.push(node);
}
while (stack.size() > 1) {
stack.pop();
}
return stack.peek();
}
}
Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1028 (Recover a Tree From Preorder Traversal)?
This page provides optimized solutions for LeetCode problem 1028 (Recover a Tree From Preorder Traversal) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1028 (Recover a Tree From Preorder Traversal)?
The time complexity for LeetCode 1028 (Recover a Tree From Preorder Traversal) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1028 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1028 in Java, C++, or Python.