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”]
题意:给定二叉树,返回所有路径
思路:DFS
代码:
/**
* 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> path = new ArrayList<String>();
if(root != null){
dfs(root, "", path);
}
return path;
}
private void dfs(TreeNode root, String str, List<String> path){
if(root.left == null && root.right == null){
path.add(str + root.val);
}
if(root.left != null){
dfs(root.left, str + root.val + "->", path);
}
if(root.right != null){
dfs(root.right, str + root.val + "->", path);
}
}
}