You are given a string representing the preorder depth-first search (DFS) traversal of a binary tree. In this traversal, each node is output as a series of dashes followed by its integer value. The number of dashes indicates the node's depth in the tree:
Your task is to reconstruct the original binary tree from this traversal string and return the tree's root.
Implement a function that, given the preorder traversal string, recovers the binary tree and returns its root.
Input:
traversal = "10-20--30--40-50--60--70"
Output:
[10, 20, 50, 30, 40, 60, 70]
Explanation:
Input:
traversal = "8-9--10---11-12--13---14"
[8, 9, 12, 10, null, 13, null, 11, null, 14]
Explanation:
Input:
traversal = "100-200--300---400---500-600--700"
Output:
[100, 200, 600, 300, null, 700, null, 400, 500]
Explanation:
https://leetcode.com/problems/recover-a-tree-from-preorder-traversal/description
Loading component...
Loading component...
Main Function is not defined.
INPUT: 10-20--30--40-50--60--70
OUTPUT: [10, 20, 50, 30, 40, 60, 70]
public TreeNode recoverFromPreorder(String traversal) {
Stack<TreeNode> stack = new Stack<>();
int i = 0;
int n = traversal.length();
while (i < n) {
int depth = 0;
while (i < n && traversal.charAt(i) == '-') {
depth++;
i++;
}//Loop End
int value = 0;
while (i < n && Character.isDigit(traversal.charAt(i))) {
value = value * 10 + (traversal.charAt(i) - '0');
i++;
}//Loop End
TreeNode node = new TreeNode(value);
while (stack.size() > depth) {
stack.pop();
}//Loop End
if (!stack.isEmpty()) {
TreeNode parent = stack.peek();
if (parent.left == null) {
parent.left = node;
}//If End
else {
parent.right = node;
}//Else End
}//If End
stack.push(node);
}//Loop End
while (stack.size() > 1) {
stack.pop();
}//Loop End
return stack.peek();
}//function end
Utility Function is not required.