-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
Copy path0988-smallest-string-starting-from-leaf.js
53 lines (44 loc) · 1.2 KB
/
0988-smallest-string-starting-from-leaf.js
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
/**
* 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)
* }
*/
/**
* Tree | Backtracking
* Time O(n^2) | Space O(n)
* https://leetcode.com/problems/smallest-string-starting-from-leaf/
* @param {TreeNode} root
* @return {string}
*/
var smallestFromLeaf = function(root) {
let biggestStr = new Array(8500).fill("z");
biggestStr = biggestStr.join("");
let smallest = biggestStr;
const dfs = (node, str) => {
const char = String.fromCharCode(node.val+97);
if (!node.left && !node.right) {
str.push(char);
const str1 = str.slice(0).reverse().join("");
if (str1 < smallest) {
smallest = str1;
}
str.pop();
return;
}
if (node.left) {
str.push(char);
dfs(node.left, str);
str.pop();
}
if (node.right) {
str.push(char);
dfs(node.right, str);
str.pop();
}
}
dfs(root,[]);
return smallest;
};