|
| 1 | +/** |
| 2 | + * 536. Construct Binary Tree from String |
| 3 | + * https://leetcode.com/problems/construct-binary-tree-from-string/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * You need to construct a binary tree from a string consisting of parenthesis and integers. |
| 7 | + * |
| 8 | + * The whole input represents a binary tree. It contains an integer followed by zero, one or |
| 9 | + * two pairs of parenthesis. The integer represents the root's value and a pair of parenthesis |
| 10 | + * contains a child binary tree with the same structure. |
| 11 | + * |
| 12 | + * You always start to construct the left child node of the parent first if it exists. |
| 13 | + */ |
| 14 | + |
| 15 | +/** |
| 16 | + * Definition for a binary tree node. |
| 17 | + * function TreeNode(val, left, right) { |
| 18 | + * this.val = (val===undefined ? 0 : val) |
| 19 | + * this.left = (left===undefined ? null : left) |
| 20 | + * this.right = (right===undefined ? null : right) |
| 21 | + * } |
| 22 | + */ |
| 23 | +/** |
| 24 | + * @param {string} s |
| 25 | + * @return {TreeNode} |
| 26 | + */ |
| 27 | +var str2tree = function(s) { |
| 28 | + if (!s) return null; |
| 29 | + let index = 0; |
| 30 | + return constructTree(); |
| 31 | + |
| 32 | + function parseNumber() { |
| 33 | + const isNegative = s[index] === '-'; |
| 34 | + if (isNegative) index++; |
| 35 | + |
| 36 | + let num = 0; |
| 37 | + while (index < s.length && /[0-9]/.test(s[index])) { |
| 38 | + num = num * 10 + parseInt(s[index]); |
| 39 | + index++; |
| 40 | + } |
| 41 | + |
| 42 | + return isNegative ? -num : num; |
| 43 | + } |
| 44 | + |
| 45 | + function constructTree() { |
| 46 | + if (index >= s.length) return null; |
| 47 | + |
| 48 | + const value = parseNumber(); |
| 49 | + const node = new TreeNode(value); |
| 50 | + if (index < s.length && s[index] === '(') { |
| 51 | + index++; |
| 52 | + node.left = constructTree(); |
| 53 | + index++; |
| 54 | + } |
| 55 | + |
| 56 | + if (index < s.length && s[index] === '(') { |
| 57 | + index++; |
| 58 | + node.right = constructTree(); |
| 59 | + index++; |
| 60 | + } |
| 61 | + |
| 62 | + return node; |
| 63 | + } |
| 64 | +}; |
0 commit comments