-
Notifications
You must be signed in to change notification settings - Fork 0
/
smallestFromLeaf.ts
47 lines (35 loc) · 941 Bytes
/
smallestFromLeaf.ts
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
import { TreeNode } from 'classes/BinaryTreeNode'
import { numToLowercaseChar } from 'utils/char/numToLowercaseChar'
// <Recursion, DFS>
// Time: O(n)
// Space: O(n)
interface Helper {
smallestStr: string
}
// 1. dfs
function dfs(node: TreeNode | null, helper: Helper, curStr = '') {
// edge cases
if (!node) {
return
}
// 2. pre-order traversal
curStr = numToLowercaseChar(node.val) + curStr
if (!node.left && !node.right) {
if (helper.smallestStr === '' || helper.smallestStr > curStr) {
helper.smallestStr = curStr
}
return
}
if (node.left) {
dfs(node.left, helper, curStr)
}
if (node.right) {
dfs(node.right, helper, curStr)
}
}
function smallestFromLeaf(root: TreeNode | null): string {
const helper: Helper = { smallestStr: '' }
dfs(root, helper)
return helper.smallestStr
}
export { smallestFromLeaf }