Skip to content

Commit f84d835

Browse files
committed
Add solution #1028
1 parent d20d73a commit f84d835

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed

Diff for: README.md

+1
Original file line numberDiff line numberDiff line change
@@ -437,6 +437,7 @@
437437
1010|[Pairs of Songs With Total Durations Divisible by 60](./1010-pairs-of-songs-with-total-durations-divisible-by-60.js)|Medium|
438438
1022|[Sum of Root To Leaf Binary Numbers](./1022-sum-of-root-to-leaf-binary-numbers.js)|Easy|
439439
1023|[Camelcase Matching](./1023-camelcase-matching.js)|Medium|
440+
1028|[Recover a Tree From Preorder Traversal](./1028-recover-a-tree-from-preorder-traversal.js)|Hard|
440441
1037|[Valid Boomerang](./1037-valid-boomerang.js)|Easy|
441442
1041|[Robot Bounded In Circle](./1041-robot-bounded-in-circle.js)|Medium|
442443
1047|[Remove All Adjacent Duplicates In String](./1047-remove-all-adjacent-duplicates-in-string.js)|Easy|
+55
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
/**
2+
* 1028. Recover a Tree From Preorder Traversal
3+
* https://leetcode.com/problems/recover-a-tree-from-preorder-traversal/
4+
* Difficulty: Hard
5+
*
6+
* We run a preorder depth-first search (DFS) on the root of a binary tree.
7+
*
8+
* At each node in this traversal, we output D dashes (where D is the depth of this node),
9+
* then we output the value of this node. If the depth of a node is D, the depth of its
10+
* immediate child is D + 1. The depth of the root node is 0.
11+
*
12+
* If a node has only one child, that child is guaranteed to be the left child.
13+
*
14+
* Given the output traversal of this traversal, recover the tree and return its root.
15+
*/
16+
17+
/**
18+
* Definition for a binary tree node.
19+
* function TreeNode(val, left, right) {
20+
* this.val = (val===undefined ? 0 : val)
21+
* this.left = (left===undefined ? null : left)
22+
* this.right = (right===undefined ? null : right)
23+
* }
24+
*/
25+
/**
26+
* @param {string} traversal
27+
* @return {TreeNode}
28+
*/
29+
var recoverFromPreorder = function(traversal) {
30+
const stack = [];
31+
32+
for (let i = 0; i < traversal.length;) {
33+
let depth = 0;
34+
while (traversal[i] === '-') {
35+
depth++;
36+
i++;
37+
}
38+
39+
let value = 0;
40+
while (i < traversal.length && traversal[i] !== '-') {
41+
value = value * 10 + parseInt(traversal[i]);
42+
i++;
43+
}
44+
45+
const node = new TreeNode(value);
46+
while (stack.length > depth) stack.pop();
47+
if (stack.length) {
48+
if (!stack[stack.length - 1].left) stack[stack.length - 1].left = node;
49+
else stack[stack.length - 1].right = node;
50+
}
51+
stack.push(node);
52+
}
53+
54+
return stack[0];
55+
};

0 commit comments

Comments
 (0)