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"]
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
Subscribe to see which companies asked this question.
Solution:
Tips:
tree, recursion
Java Code:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> result = new ArrayList<>();
if (null == root) {
return result;
}
binaryTreePaths(root, "", result);
return result;
}
// root cann't be null
private void binaryTreePaths(TreeNode root, String str, List<String> result) {
if (root.left == null && root.right == null) {
result.add(str + root.val);
return;
}
str = str + root.val + "->";
if (root.left != null) {
binaryTreePaths(root.left, str, result);
}
if (root.right != null) {
binaryTreePaths(root.right, str, result);
}
}
}