|
| 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