Skip to content

Commit 6fb3ecd

Browse files
committedJun 4, 2022
Smallest String Starting From Leaf
1 parent cde513a commit 6fb3ecd

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed
 

‎README.md

+1
Original file line numberDiff line numberDiff line change
@@ -56,4 +56,5 @@
5656
|897|[递增顺序搜索树](https://leetcode.cn/problems/increasing-order-search-tree/)|[JavaScript](./algorithms/increasing-order-search-tree.js)|Easy|
5757
|912|[排序数组](https://leetcode.cn/problems/sort-an-array/)|[JavaScript](./algorithms/sort-an-array.js)|Medium|
5858
|965|[单值二叉树](https://leetcode.cn/problems/univalued-binary-tree/)|[JavaScript](./algorithms/univalued-binary-tree.js)|Easy|
59+
|988|[从叶结点开始的最小字符串](https://leetcode.cn/problems/smallest-string-starting-from-leaf/)|[JavaScript](./algorithms/smallest-string-starting-from-leaf.js)|Medium|
5960
|面试题 04.12|[面试题 04.12. 求和路径](https://leetcode.cn/problems/paths-with-sum-lcci/)|[JavaScript](./algorithms/paths-with-sum-lcci.js)|Medium|
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* function TreeNode(val, left, right) {
4+
* this.val = (val===undefined ? 0 : val)
5+
* this.left = (left===undefined ? null : left)
6+
* this.right = (right===undefined ? null : right)
7+
* }
8+
*/
9+
/**
10+
* 从叶结点开始的最小字符串
11+
* @param {TreeNode} root
12+
* @return {string}
13+
*/
14+
var smallestFromLeaf = function (root) {
15+
const str = "abcdefghijklmnopqrstuvwxyz";
16+
let minPath = "";
17+
const dfs = (node, path = "") => {
18+
if (node) {
19+
path = str[node.val] + path;
20+
// leaf node
21+
if (!node.left && !node.right) {
22+
if (!minPath || minPath > path) {
23+
minPath = path;
24+
}
25+
}
26+
dfs(node.left, path);
27+
dfs(node.right, path);
28+
}
29+
};
30+
dfs(root);
31+
return minPath;
32+
};

0 commit comments

Comments
 (0)