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