1
var smallestFromLeaf = function (root) {
2
if (root === null) return "";
3

4
let queue = [[root, "" + giveCharacter(root.val)]];
5
let leafLevelFound = false;
6
let possibleSmallString = [];
7

8
while (queue.length > 0) {
9
let currentLevelLength = queue.length;
10

11
for (let i = 0; i < currentLevelLength; i++) {
12
let [currentNode, currentPath] = queue.shift();
13

14
if (currentNode.left === null && currentNode.right === null) {
15
// as one of the test case is failing with this approacch - saying legth/depth of the path doesnt matter
16
// even TOTAL (ASCII)SUM of letters also not matter - it should be dictionary first path
17
// hence, no need of this logic and have to continue until all path discovered
18
// So, instead removing - just never doing TRUE - hence it will continue exploring and putting all paths
19
leafLevelFound = false;
20
possibleSmallString.push(currentPath); //.split("").reverse().join("")
21
}
22

23
if (!leafLevelFound) {
24
if (currentNode.left !== null)
25
queue.push([
26
currentNode.left,
27
giveCharacter(currentNode.left.val) + currentPath,
28
]);
29
if (currentNode.right !== null)
30
queue.push([
31
currentNode.right,
32
giveCharacter(currentNode.right.val) + currentPath,
33
]);
34
}
35
}
36

37
if (leafLevelFound) break;
38
}
39

40
// console.log(possibleSmallString);
41
possibleSmallString.sort();
42
// console.log(possibleSmallString);
43
return possibleSmallString[0];
44
};
45

46
function giveCharacter(num) {
47
return String.fromCharCode(num + 97);
48
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0