-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSmallestStringStartingFromLeaf.cs
More file actions
52 lines (42 loc) · 1.46 KB
/
SmallestStringStartingFromLeaf.cs
File metadata and controls
52 lines (42 loc) · 1.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
using System;
using System.Collections.Generic;
using System.Text;
namespace CodeForecs
{
//https://leetcode.com/problems/smallest-string-starting-from-leaf/
class SmallestStringStartingFromLeaf
{
public string SmallestFromLeaf(TreeNode root)
{
StringBuilder result = new StringBuilder();
SmallestFromLeafHelper(root, result, "");
return result.ToString();
}
public void SmallestFromLeafHelper(TreeNode root, StringBuilder result, string pathString)
{
if (root == null)
{
return;
}
if (root.left == null && root.right == null)
{
//Add the character backwards to avoid reversing the string later.
pathString = Convert.ToChar('a' + root.val) + pathString;
if(result.ToString() == string.Empty)
{
result.Append(pathString);
}
else if(string.Compare(result.ToString(), pathString) > 0)
{
result.Clear();
result.Append(pathString);
}
//Console.WriteLine(result);
return;
}
pathString = Convert.ToChar('a' + root.val) + pathString;
SmallestFromLeafHelper(root.left, result, pathString);
SmallestFromLeafHelper(root.right, result, pathString);
}
}
}