LeetCode Q 1028 - Recover a Tree From Preorder Traversal
We run a preorder depth first search on the root of a binary tree.
At each node in this traversal, we output D
dashes (where D is the depth of this node), then we output the value of this node. (If the depth of a node is D, the depth of its immediate child is D+1. The depth of the root node is 0.)
If a node has only one child, that child is guaranteed to be the left child.
Given the output S of this traversal, recover the tree and return its root.
Example 1: Input: "1-2--3--4-5--6--7" ; Output: [1,2,5,3,4,6,7]
Example 2: Input: "1-2--3---4-5--6---7" ; Output: [1,2,5,3,null,6,null,4,null,7]
Example 3: Input: "1-401--349---90--88" ; Output: [1,401,null,349,88,90]
Note:
- The number of nodes in the original tree is between 1 and 1000.
- Each node will have a value between 1 and 10^9.
Solution: Using Stack
Code:
public TreeNode recoverFromPreorder(String S) {
Deque<TreeNode> stack = new ArrayDeque<>();
for (int i = 0; i < S.length(); ) {
int depth = 0;
while (i < S.length() && S.charAt(i) == '-') { depth++; i++; }
int val = 0;
while (i < S.length() && Character.isDigit(S.charAt(i))) {
val = val * 10 + S.charAt(i++) - '0';
}
TreeNode node = new TreeNode(val);
while (stack.size() > depth) stack.pop();
if (!stack.isEmpty() && stack.peek().left == null)
stack.peek().left = node;
else if (!stack.isEmpty() && stack.peek().left != null)
stack.peek().right = node;
stack.push(node);
}
return stack.peekLast();
}
The key point is in the stack, we only store a branch. For example, in this tree we first store 1, 2, 4 in the stack, 1 is 2’s parent, and 2 is 4’s parent.
What should we do if we encounter another child of a node. We just pop numbers in the stack to make stack.size() == depth
. For example,