题目链接:https://leetcode-cn.com/problems/binary-tree-paths/description/
给定一个二叉树,返回所有从根节点到叶子节点的路径。
说明: 叶子节点是指没有子节点的节点。
示例:
输入:
1
/ \
2 3
\
5
输出: ["1->2->5", "1->3"]
解释: 所有根节点到叶子节点的路径为: 1->2->5, 1->3
/**
* 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> mlists=new ArrayList<String>();
public void dfs(TreeNode root,String str){
if(root.left==null&&root.right==null){
mlists.add(str);
return ;
}
if(root.left!=null){
dfs(root.left, str+"->"+root.left.val);
}
if(root.right!=null){
dfs(root.right, str+"->"+root.right.val);
}
}
public List<String> binaryTreePaths(TreeNode root) {
if(root==null){
return mlists;
}
dfs(root,String.valueOf(root.val));
return mlists;
}
}