链接:https://leetcode-cn.com/problems/smallest-string-starting-from-leaf/submissions/
dfs遍历树,查看每个可能的字符串,记录当前最小的字符串。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
String ans = "~";
public String smallestFromLeaf(TreeNode root) {
StringBuilder stb = new StringBuilder();
dfs(root,stb);
return ans;
}
private void dfs(TreeNode root, StringBuilder stb)
{
if(root==null)
return;
char c = (char)(root.val+97);
stb.append(c);
if(root.left==null&&root.right==null)
{
String S = stb.reverse().toString();
if (S.compareTo(ans) < 0)
ans = S;
return;
}
dfs(root.left,new StringBuilder(stb));
dfs(root.right,new StringBuilder(stb));
}
}