http://www.lintcode.com/en/problem/binary-tree-paths/
Given a binary tree, return all root-to-leaf paths.
Example
Given the following binary tree:
1
/ \
2 3
\
5
All root-to-leaf paths are:
[
"1->2->5",
"1->3"
]
解题:要求所有从root到leaf的路径,一般的遍历都可以,注意处理一下结果需要的字符串就好了。
public class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> result = new ArrayList<String>();
if (root != null) {
findPath(result, root, String.valueOf(root.val));
}
return result;
}
public void findPath(List<String> result, TreeNode p, String path) {
if(p == null) {
return ;
}
//到leaf,左右都为空的时候
if (p.left == null && p.right == null) {
result.add(path);
return ;
}
//左子树不为空的时候
if(p.left != null) {
findPath(result, p.left, path + "->" + String.valueOf(p.left.val));
}
//右子树不为空的时候
if(p.right != null) {
findPath(result, p.right, path + "->" + String.valueOf(p.right.val));
}
}
}