代码:
/**
* 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> list = new ArrayList<>();
if(root == null) return list;
String s = "";
addTreePath(root, root.val, s, list);
return list;
}
public void addTreePath(TreeNode root, int val, String s, List<String> list){
if(root.left == null && root.right == null){
list.add(s+root.val);
}
else if(root.left != null && root.right == null){
addTreePath(root.left, val, s+root.val+"->", list);
}
else if(root.left == null && root.right != null){
addTreePath(root.right, val, s+root.val+"->", list);
}
else{
addTreePath(root.left, val, s+root.val+"->", list);
addTreePath(root.right, val, s+root.val+"->", list);
}
}
}
Jan 12 - Binary Tree Paths; Tree; Recursion; DFS;
原文:http://www.cnblogs.com/5683yue/p/5126828.html