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 List<String> binaryTreePaths(TreeNode root) {
List<String> paths = new ArrayList<String>();
if (root == null) return paths;
if (root.left == null && root.right == null) {
paths.add(root.val + "");
return paths;
}
List<String> left = binaryTreePaths(root.left);
List<String> right = binaryTreePaths(root.right);
for (String tmp : left) {
paths.add(root.val + "->" + tmp);
}
for (String tmp : right) {
paths.add(root.val + "->" + tmp);
}
return paths;
}