Skip to content

Commit 4db7ebc

Browse files
committed
Add solution #606
1 parent 5a4bb1d commit 4db7ebc

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/**
2+
* 606. Construct String from Binary Tree
3+
* https://leetcode.com/problems/construct-string-from-binary-tree/
4+
* Difficulty: Easy
5+
*
6+
* You need to construct a string consists of parenthesis and integers
7+
* from a binary tree with the preorder traversing way.
8+
*
9+
* The null node needs to be represented by empty parenthesis pair "()".
10+
* And you need to omit all the empty parenthesis pairs that don't
11+
* affect the one-to-one mapping relationship between the string
12+
* and the original binary tree.
13+
*/
14+
15+
/**
16+
* Definition for a binary tree node.
17+
* function TreeNode(val) {
18+
* this.val = val;
19+
* this.left = this.right = null;
20+
* }
21+
*/
22+
/**
23+
* @param {TreeNode} t
24+
* @return {string}
25+
*/
26+
var tree2str = function(t) {
27+
return !t ? '' : `${t.val}(${tree2str(t.left)})(${tree2str(t.right)})`.replace(/(\(\)){2}|\(\)(?=$|\))/g, '');
28+
};
29+
30+
31+
// alternative, longer but faster version:
32+
/**
33+
* @param {TreeNode} t
34+
* @return {string}
35+
*/
36+
var tree2str = function(t) {
37+
let str = t ? `${t.val}` : '';
38+
if (t && t.right) str += `(${tree2str(t.left)})(${tree2str(t.right)})`;
39+
else if (t && t.left) str += `(${tree2str(t.left)})`;
40+
return str;
41+
};

0 commit comments

Comments
 (0)