样例
给出下面这棵二叉树:
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) {
// Write your code here
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;
}
paths.add(path);//到叶子节点 将路径字符串加入list
}
//非叶子节点 将节点加入字符串保存
if (path.equals("")){
path += root.val;
}
else {
path += "->" + root.val;
}
searchPaths(root.left, paths, path);
searchPaths(root.right, paths, path);
}
}