988. Smallest String Starting From Leaf #206
-
Difficulty: Medium Topics: You are given the 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.
A leaf of a node is a node that has no children. Example 1:
Example 2:
Example 3:
Constraints:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
This problem is based on finding the lexicographically smallest string that starts at a leaf node and ends at the root in a binary tree. Each node contains a value between 0 and 25, representing the letters 'a' to 'z'. You are required to return the smallest string in lexicographical order formed by the path from any leaf node to the root node. Key Points
ApproachTo solve this problem, we use Depth-First Search (DFS) with a backtracking approach:
Plan
Let's implement this solution in PHP: 988. Smallest String Starting From Leaf <?php
/**
* @param TreeNode $root
* @return String
*/
function smallestFromLeaf(TreeNode $root): string
{
$ans = "";
dfs($root, "", $ans);
return $ans;
}
/**
* @param $root
* @param $path
* @param $ans
* @return void
*/
private function dfs($root, $path, &$ans): void
{
if ($root == null)
return;
// Append the current node value as a character.
$path .= chr($root->val + ord('a'));
// If it's a leaf node, compare the current path with the answer.
if ($root->left == null && $root->right == null) {
$path = strrev($path); // Reverse the path to match leaf-to-root order.
if ($ans == "" || $ans > $path)
$ans = $path;
$path = strrev($path); // Roll back the change for backtracking.
}
// DFS recursion for left and right children.
dfs($root->left, $path, $ans);
dfs($root->right, $path, $ans);
// Backtrack: remove the last character.
$path = substr($path, 0, -1);
}
// Example 1
$root = [0,1,2,3,4,3,4];
echo smallestFromLeaf($root); // Output: "dba"
// Example 2
$root = [25,1,3,1,3,0,2];
echo smallestFromLeaf($root); // Output: "adz"
// Example 3
$root = [2,2,1,null,1,0,null,0];
echo smallestFromLeaf($root); // Output: "abc"
?> Explanation:
Example WalkthroughExample 1:Tree structure:
Example 2:Tree structure:
Time Complexity
Space Complexity
Output for Example
This approach uses Depth-First Search (DFS) with backtracking to explore all paths from leaf nodes to the root while maintaining the lexicographically smallest string. The solution efficiently handles the problem within the constraints and ensures that we find the correct smallest string for each given tree structure. |
Beta Was this translation helpful? Give feedback.
This problem is based on finding the lexicographically smallest string that starts at a leaf node and ends at the root in a binary tree. Each node contains a value between 0 and 25, representing the letters 'a' to 'z'. You are required to return the smallest string in lexicographical order formed by the path from any leaf node to the root node.
Key Points