Skip to content

Commit cb1d06e

Browse files
authored
Create 988-smallest-string-starting-from-leaf.js
1 parent 30e956a commit cb1d06e

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* function TreeNode(val) {
4+
* this.val = val;
5+
* this.left = this.right = null;
6+
* }
7+
*/
8+
/**
9+
* @param {TreeNode} root
10+
* @return {string}
11+
*/
12+
const smallestFromLeaf = function(root) {
13+
const res = []
14+
chk(root, [], res)
15+
res.sort()
16+
return res[0]
17+
};
18+
19+
function chk(node, path, res) {
20+
if(node == null) return
21+
path.push(node.val)
22+
if(node.left == null && node.right == null) {
23+
res.push(arrToStr( path.slice(0).reverse() ))
24+
return
25+
}
26+
chk(node.left, path.slice(0), res)
27+
chk(node.right, path.slice(0), res)
28+
}
29+
30+
function numToChar(num) {
31+
const str = 'abcdefghijklmnopqrstuvwxyz'
32+
return str[num]
33+
}
34+
35+
function arrToStr(arr) {
36+
let res = ''
37+
for(let i = 0; i < arr.length; i++) {
38+
res += numToChar(arr[i])
39+
}
40+
return res
41+
}

0 commit comments

Comments
 (0)