Given a binary tree, return all root-to-leaf paths.
For example, given the following binary tree:
1
/ \
2 3
\
5
All root-to-leaf paths are:
["1->2->5", "1->3"]
解题思路:
代码应该看得懂,先序遍历,处理字符串。
public class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> string = new ArrayList<String>();
List<String> temp;
if(root == null)
return string;
if(root.left == null && root.right == null){
string.add(root.val+"");
return string;
}
temp = binaryTreePaths(root.left);
for(int i = 0; i < temp.size(); i++){
string.add(root.val + "->" + temp.get(i));
}
temp = binaryTreePaths(root.right);
for(int i = 0; i < temp.size(); i++){
string.add(root.val + "->" + temp.get(i));
}
return string;
}
}