/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */
public class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> str = new ArrayList<String>();
if (root == null)
return str;
PathsDFS(root, "", str);
return str;
}
public static void PathsDFS(TreeNode root, String s, List<String> str) {
if (root.left == null && root.right == null) {
s += root.val;
str.add(s);
}
if (root.left != null)
PathsDFS(root.left, s + root.val + "->", str);
if (root.right != null)
PathsDFS(root.right, s + root.val + "->", str);
}
}
还没有评论,来说两句吧...