Untitled
public class SmallestStringFromLeaf { private static String smallestString; public static String smallestFromLeaf(TreeNode root) { smallestString = null; // Initialize the smallest string as null dfs(root, new StringBuilder()); return smallestString; } private static void dfs(TreeNode node, StringBuilder currentString) { if (node == null) return; // Prepend the current character to the path string currentString.insert(0, (char) ('a' + node.val)); // If it's a leaf node, compare the current string to the smallest string if (node.left == null && node.right == null) { String currentPath = currentString.toString(); if (smallestString == null || currentPath.compareTo(smallestString) < 0) { smallestString = currentPath; } } // Recurse on the left and right children dfs(node.left, currentString); dfs(node.right, currentString); // Backtrack: Remove the current character from the path currentString.deleteCharAt(0); }
Leave a Comment