从根开始遍历,分析左右子节点状态判断叶子节点以及当前节点是否应该加“->”
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
List<String> res=new ArrayList<String>();
public List<String> binaryTreePaths(TreeNode root) {
if( root==null )
{
return res;
}
String str=root.val+"";
if( root.right==null&&root.left==null )
{
res.add(str);
return res;
}
fun( root.left,str );
fun( root.right,str );
return res;
}
void fun( TreeNode root,String str )
{
if( root==null )
{
return ;
}
str+="->"+root.val;
if( root.left==null&&root.right==null )
{
res.add(str);
}
fun( root.left,str );
fun( root.right,str );
}
}