# 二叉树的所有路径

1
/   \
2     3
\
5

[
"1->2->5",
"1->3"
]

/**

* Definition of TreeNode:
* public class TreeNode {
*     public int val;
*     public TreeNode left, right;
*     public TreeNode(int val) {
*         this.val = val;
*         this.left = this.right = null;
*     }
* }
*/
public class Solution {
/**
* @param root the root of the binary tree
* @return all root-to-leaf paths
* 根左右 遍历
*/
public List<String> binaryTreePaths(TreeNode root) {
ArrayList<String> paths = new ArrayList<String>();
String path = "";
if (root == null){
return paths;
}
searchPaths(root, paths, path);
return paths;
}
public void searchPaths(TreeNode root, ArrayList<String> paths, String path){
if (root == null){
return;
}
if (root.left == null && root.right == null){
if (path.equals("")){
path += root.val;
}
else {
path += "->" + root.val;
}
}
//非叶子节点 将节点加入字符串保存
if (path.equals("")){
path += root.val;
}
else {
path += "->" + root.val;
}
searchPaths(root.left, paths, path);
searchPaths(root.right, paths, path);
}
}

06-11 42

04-10 185

04-21 332

07-04 103

07-20 8

05-27 62

06-30 15

07-10 7

04-14 399

04-07 2310