Skip to content

Commit f71f609

Browse files
authored
Create 0606-construct-string-from-binary-tree.js
1 parent f5488aa commit f71f609

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

Diff for: javascript/0606-construct-string-from-binary-tree.js

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/**
2+
* InOrder Traversal
3+
* Time O(n) | Space O(n)
4+
* https://leetcode.com/problems/construct-string-from-binary-tree/
5+
* Definition for a binary tree node.
6+
* function TreeNode(val, left, right) {
7+
* this.val = (val===undefined ? 0 : val)
8+
* this.left = (left===undefined ? null : left)
9+
* this.right = (right===undefined ? null : right)
10+
* }
11+
*/
12+
/**
13+
* @param {TreeNode} root
14+
* @return {string}
15+
*/
16+
var tree2str = function(root) {
17+
18+
let str = "";
19+
const dfs = (node) => {
20+
if(!node) return;
21+
str += node.val;
22+
if(node.right || node.left) str += "(";
23+
dfs(node.left);
24+
if(node.right || node.left) str += ")";
25+
26+
// right tree
27+
if(node.right) str += "(";
28+
dfs(node.right);
29+
if(node.right) str += ")";
30+
}
31+
32+
dfs(root);
33+
return str;
34+
};

0 commit comments

Comments
 (0)