标签:题解 代码 返回 class str get solution efi link
给定一个二叉树,返回所有从根节点到叶子节点的路径。
例:输出: ["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> binaryTreePaths(TreeNode root) {
List<String> list = new LinkedList<>();
String s = "";
getPaths(root,s,list);
return list;
}
public void getPaths(TreeNode root,String path,List<String> ans){
if(root!=null){
path+=root.val;
if(root.left==null&&root.right==null){
ans.add(path);
}
else{
path+="->";
getPaths(root.left,path,ans);
getPaths(root.right,path,ans);
}
}
}
}
标签:题解 代码 返回 class str get solution efi link
原文地址:https://www.cnblogs.com/coding-gaga/p/13040965.html