# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def smallestFromLeaf(self, root: Optional[TreeNode]) -> str:
self.result = "~" # '~' is lexicographically larger than any lowercase string
def dfs(node, path):
if not node:
return
# Prepend current character to path (since we want leaf-to-root)
path = chr(ord('a') + node.val) + path
if not node.left and not node.right:
if path < self.result:
self.result = path
dfs(node.left, path)
dfs(node.right, path)
dfs(root, "")
return self.result
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
string result = "~";
void dfs(TreeNode* node, string path) {
if (!node) return;
path = char('a' + node->val) + path;
if (!node->left && !node->right) {
if (path < result) result = path;
}
dfs(node->left, path);
dfs(node->right, path);
}
string smallestFromLeaf(TreeNode* root) {
dfs(root, "");
return result;
}
};
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
private String result = "~";
public String smallestFromLeaf(TreeNode root) {
dfs(root, "");
return result;
}
private void dfs(TreeNode node, String path) {
if (node == null) return;
path = (char)('a' + node.val) + path;
if (node.left == null && node.right == null) {
if (path.compareTo(result) < 0) result = path;
}
dfs(node.left, path);
dfs(node.right, path);
}
}
/**
* 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 = "~";
function dfs(node, path) {
if (!node) return;
path = String.fromCharCode(97 + node.val) + path;
if (!node.left && !node.right) {
if (path < result) result = path;
}
dfs(node.left, path);
dfs(node.right, path);
}
dfs(root, "");
return result;
};
0 / \ 1 2 / 3Where node values map as: 0 - 'a', 1 - 'b', 2 - 'c', 3 - 'd'.