Skip to content

Commit f498eab

Browse files
committed
Add solution #536
1 parent 01a72d3 commit f498eab

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -521,6 +521,7 @@
521521
532|[K-diff Pairs in an Array](./solutions/0532-k-diff-pairs-in-an-array.js)|Medium|
522522
533|[Lonely Pixel II](./solutions/0533-lonely-pixel-ii.js)|Medium|
523523
535|[Encode and Decode TinyURL](./solutions/0535-encode-and-decode-tinyurl.js)|Medium|
524+
536|[Construct Binary Tree from String](./solutions/0536-construct-binary-tree-from-string.js)|Medium|
524525
537|[Complex Number Multiplication](./solutions/0537-complex-number-multiplication.js)|Medium|
525526
538|[Convert BST to Greater Tree](./solutions/0538-convert-bst-to-greater-tree.js)|Medium|
526527
539|[Minimum Time Difference](./solutions/0539-minimum-time-difference.js)|Medium|
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
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

Comments
 (0)