問題描述:
Given a binary tree, return all root-to-leaf paths.
For example, given the following binary tree:
代碼:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> result = new ArrayList<>();
if(root == null) return result;
String s = "";
dfs(root, s, result);
return result;
}
public void dfs(TreeNode root, String s, List<String> result){
s += root.val;
if(root.left == null && root.right == null)
result.add(s);
if(root.left != null){
dfs(root.left, s+"->", result);
}
if(root.right != null)
dfs(root.right, s+"->", result);
}
}