-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy path0988-smallest-string-starting-from-leaf.js
52 lines (47 loc) · 1.32 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
/**
* 988. Smallest String Starting From Leaf
* https://leetcode.com/problems/smallest-string-starting-from-leaf/
* Difficulty: Medium
*
* You are given the root of a binary tree where each node has a value in the range [0, 25]
* representing the letters 'a' to 'z'.
*
* Return the lexicographically smallest string that starts at a leaf of this tree and ends
* at the root.
*
* As a reminder, any shorter prefix of a string is lexicographically smaller.
*
* For example, "ab" is lexicographically smaller than "aba".
*
* A leaf of a node is a node that has no children.
*/
/**
* 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)
* }
*/
/**
* @param {TreeNode} root
* @return {string}
*/
var smallestFromLeaf = function(root) {
let result = null;
traverse(root, []);
return result || '';
function traverse(node, path) {
if (!node) return;
path.unshift(String.fromCharCode(node.val + 97));
if (!node.left && !node.right) {
const current = path.join('');
if (!result || current < result) {
result = current;
}
}
traverse(node.left, path);
traverse(node.right, path);
path.shift();
}
};