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; }
* }
*/
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> res= new ArrayList<String>();
if(root != null){
DFS(root,"",res);
}
return res;
}
public void DFS(TreeNode root, String val, List<String> res){
if(root.left == null && root.right == null){
res.add(val+root.val);
}
if(root.left != null){
DFS(root.left, val+ root.val+"->",res);
}
if(root.right != null){
DFS(root.right, val+ root.val+"->",res);
}
}
}
微信扫一扫
支付宝扫一扫