Grokking Tree Coding Patterns for Interviews
Ask Author
Back to course home

0% completed

Vote For New Content
Solution: Smallest String Starting From Leaf
On this page

Problem Statement

Examples

Solution

Step-by-Step Algorithm

Algorithm Walkthrough

Code

Complexity Analysis

Time Complexity

Space Complexity

Problem Statement

You are given a binary tree where each node contains a value between 0 and 25. These values correspond to the letters 'a' to 'z' (0 = 'a', 1 = 'b', ..., 25 = 'z').

Return the lexicographically smallest string that can be formed by starting from a leaf node (a node with no children) and ending at the root of the tree. The string formed should be the lexicographically smallest among all possible strings.

Remember, any shorter prefix of a string is lexicographically smaller. For example, in lexicographical order, "ab" is smaller than "aba".

Examples

Example 1:

  • Input: root = [0, 1, 2, null, 3, 3, 4]
Image
  • Expected Output: "dba"
  • Explanation: The strings formed from the leaf nodes to the root are "dba", "dca", and "eca". The smallest string is "dba".

Example 2:

  • Input: root = [4, 0, 1, 1, 3, 2, 3]
Image
  • Expected Output: "bae"
  • Explanation: The strings formed are "bae", "dae", "cbe", and "dbe". The smallest string is "bae".

Example 3:

  • Input: root = [1, 3, 2, 3, 4, 4, 3]
Image
  • Expected Output: "dcb"
  • Explanation: The strings formed are "ddb", "edb", "ecb", and "dcb". The smallest string is "dcb".

Constraints:

  • The number of nodes in the tree is in the range [1, 8500].
  • 0 <= Node.val <= 25

Solution

To solve this problem, we employ a Depth First Search (DFS) approach to traverse the binary tree from the root to all leaf nodes. As we visit each node, we construct strings by converting the node's value to its corresponding character and appending it to a suffix string. When a leaf node is reached, the constructed string, which represents the path from that leaf to the root, is returned.

The algorithm then compares these strings from different paths, ensuring that the smallest lexicographically string is selected. By using DFS, we efficiently explore all possible paths, and by maintaining the smallest string found so far, we ensure that the final result is the smallest possible string starting from a leaf and moving towards the root.

Step-by-Step Algorithm

  1. Start at the Root:

    • Start the DFS from the root node.
  2. Check for Null Node:

    • Inside the dfs method, the first action is to check if the current node (node) is null.
    • If the node is null, return a string with the value "~". This serves as a sentinel value since it is lexicographically larger than any valid string formed by the characters 'a' to 'z'.
  3. Update the Suffix String:

    • Convert the value of the current node to its corresponding character by adding the node’s value to the ASCII value of 'a'.
    • Prepend this character to the suffix string as we need to create leaf to root string.
  4. Check for Leaf Node:

    • If the current node is a leaf, return the current suffix string as it represents a valid path from a leaf to the root.
  5. Recursive DFS on Child Nodes:

    • Recursively call the dfs method on both the left and right children of the current node.
    • Pass the updated suffix string in these recursive calls.
  6. Compare and Select the Smaller String:

    • Compare the strings returned by the left and right recursive calls using the minimum method.
    • The minimum method returns the lexicographically smaller string.
  7. Return the Smallest String:

    • Return the smallest string obtained from the comparisons. This string is propagated up the recursive call stack, eventually reaching the original call in the smallestFromLeaf method.

Algorithm Walkthrough

Given the binary tree structure for the input:

    0
   / \
  1   2
   \  / \
    3 3  4
  1. Start at Root:

    • The smallestFromLeaf method is called with the root node (0) and an empty string "".
  2. DFS on Root Node:

    • The dfs method starts with node 0. The current suffix is "a" because 0 + 'a' = 'a'.
    • The node 0 is not a leaf, so proceed to its children.
  3. DFS on Left Subtree (Node 1):

    • The dfs method is called recursively with node 1 and the current suffix "a".
    • The current suffix becomes "ba" because 1 + 'a' = 'b'.
    • Node 1 is not a leaf, so move to its children.
  4. DFS on Node 3 (Right Child of Node 1):

    • The dfs method is called recursively with node 3 and the current suffix "ba".
    • The current suffix becomes "dba" because 3 + 'a' = 'd'.
    • Node 3 is a leaf, so return "dba".
  5. DFS on Right Subtree (Node 2):

    • After completing the left subtree, the algorithm moves to the right subtree by calling dfs on node 2 with the initial suffix "a".
    • The current suffix becomes "ca" because 2 + 'a' = 'c'.
    • Node 2 is not a leaf, so move to its children.
  6. DFS on Node 3 (Left Child of Node 2):

    • The dfs method is called recursively with node 3 and the current suffix "ca".
    • The current suffix becomes "dca" because 3 + 'a' = 'd'.
    • Node 3 is a leaf, so return "dca".
  7. DFS on Node 4 (Right Child of Node 2):

    • The dfs method is called recursively with node 4 and the current suffix "ca".
    • The current suffix becomes "eca" because 4 + 'a' = 'e'.
    • Node 4 is a leaf, so return "eca".
  8. Compare Strings from Right Subtree:

    • The algorithm now has two strings from the right subtree: "dca" and "eca".
    • Compare these strings using the minimum method. "dca" is smaller, so "dca" is returned up the call stack.
  9. Compare Left and Right Subtree Results:

    • The algorithm compares "dba" (from the left subtree) and "dca" (from the right subtree) at the root node.
    • "dba" is smaller, so "dba" is returned as the final result.
  10. Output the Result:

    • The smallest string "dba" is printed as the output.

Code

Python3
Python3

. . . .

Complexity Analysis

Time Complexity

  • The time complexity of the algorithm is O(N), where N is the number of nodes in the binary tree.
  • This is because the algorithm performs a Depth First Search (DFS), which visits each node exactly once.

Space Complexity

  • The space complexity is O(H), where H is the height of the tree.
  • This space is required for the recursive stack used during DFS. In the worst case, if the tree is skewed, the height H could be equal to N, leading to a space complexity of O(N).
  • In the best case, the tree is balanced, and the space complexity would be O(log N).

.....

.....

.....

Like the course? Get enrolled and start learning!

On this page

Problem Statement

Examples

Solution

Step-by-Step Algorithm

Algorithm Walkthrough

Code

Complexity Analysis

Time Complexity

Space Complexity