DFS + 回溯(backtracking)
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
public class Solution {
public IList<string> BinaryTreePaths(TreeNode root)
{
IList<string> result = new List<string>();
StringBuilder tmpStr = new StringBuilder();
if(root == null)
{
return result;
}
if (root.left == null && root.right == null)
{
result.Add(root.val.ToString());
return result;
}
dfs(root, tmpStr, result);
return result;
}
private void dfs(TreeNode root, StringBuilder tmpStr, IList<string> result)
{
if (root.left == null && root.right == null)
{
tmpStr.Append("->" + root.val.ToString());
result.Add(tmpStr.ToString());
return;
}
string part = root.val.ToString();
if (tmpStr.Length != 0)
{
part = "->" + part;
}
tmpStr.Append(part);
String tmptrace = tmpStr.ToString();
if (root.left != null)
{
dfs(root.left, tmpStr, result);
}
tmpStr = new StringBuilder(tmptrace);
if(root.right != null)
{
dfs(root.right, tmpStr, result);
}
}
}