257. 二叉树的所有路径
2020-06-07 本文已影响0人
编程小王子AAA
给定一个二叉树,返回所有从根节点到叶子节点的路径。
说明: 叶子节点是指没有子节点的节点。
示例:
输入:
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> binaryTreePaths(TreeNode root) {
List<String> res=new ArrayList<>();
if(root==null){
return res;
}
String temp=new String("");
help(root,temp,res);
return res;
}
private void help(TreeNode node,String temp,List<String> res){
if(node!=null){
temp+=node.val;
if(node.left==null && node.right==null){
res.add(temp);
}else{
temp+="->";
help(node.left,temp,res);
help(node.right,temp,res);
}
}
}
}