1 public class Solution 2 { 3 private Stack<string> ST = new Stack<string>(); 4 private string SmallestStr = String.Empty; 5 private string[] Ary = new string[] { "a","b","c","d","e","f","g", 6 "h","i","j","k","l","m","n","o","p","q","r","s","t", 7 "u","v","w","x","y","z"}; 8 private void SearchTree(TreeNode root) 9 { 10 if(root!=null) 11 { 12 var index = root.val; 13 var str = Ary[index]; 14 ST.Push(str); 15 16 if(root.left!=null) 17 { 18 SearchTree(root.left); 19 } 20 21 if(root.right!=null) 22 { 23 SearchTree(root.right); 24 } 25 if(root.left==null && root.right==null) 26 { 27 //find a leaf node 28 var a1 = ST.ToArray(); 29 StringBuilder sb1 = new StringBuilder(); 30 for (int i = 0; i < a1.Length;i++) 31 { 32 sb1.Append(a1[i]); 33 } 34 if(string.IsNullOrEmpty(SmallestStr) || 35 string.Compare(SmallestStr, sb1.ToString()) > 0 36 ) 37 { 38 SmallestStr = sb1.ToString(); 39 } 40 } 41 ST.Pop(); 42 } 43 } 44 45 public string SmallestFromLeaf(TreeNode root) 46 { 47 SearchTree(root); 48 return SmallestStr; 49 } 50 }
原文:https://www.cnblogs.com/asenyang/p/10353261.html