Created
April 17, 2024 16:40
-
-
Save tatsuyax25/bd460e7cd088ea0a2fabda2ff11d648d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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) { | |
// We need to initialize the smallest string as a large value | |
let smallest = "~"; | |
const dfs = (node, str) => { | |
// If the node is null, we return | |
if (!node) return; | |
// We add the current node's value (converted to a character) to the start of the string | |
str = String.fromCharCode(node.val + 97) + str; | |
// If the node is a leaf (it has no children), we compare the string with the smallest string found so far | |
if (!node.left && !node.right) { | |
if (str < smallest) smallest = str; | |
} | |
// We continue the depth-first search on the left and right children | |
dfs(node.left, str); | |
dfs(node.right, str); | |
}; | |
// We start the depth-first search from the root | |
dfs(root, ""); | |
// We return the smallest string found | |
return smallest; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment