Given a binary tree, return all root-to-leaf paths.
Note: A leaf is a node with no children.
Example:
Input: 1
/ \
2 3
\
5 Output: ["1->2->5", "1->3"] Explanation: All root-to-leaf paths are: 1->2->5, 1->3
题目
给定一棵二叉树,求出所有根到叶的路径。
思路
DFS, Very straightforward
代码
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> result = new ArrayList<>();
if(root == null) return result;
helper(root, result, "");
return result;
} private void helper (TreeNode root, List<String> result, String path){
// leaf node
if(root.left ==null && root.right ==null) {
result.add(path + root.val);
}
// dfs
if(root.left!=null){
helper(root.left, result, path+root.val+ "->");
}
if(root.right!=null){
helper(root.right, result, path+root.val+"->");
}
}
}