(easy)LeetCode 257.Binary Tree Paths

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"]

思想:递归
代码如下:
/**
* 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> ret=new ArrayList<>();
if(root==null) return ret;
String s=""+root.val;
paths(root,s,ret);
return ret;
}
public void paths(TreeNode root,String s,List<String>ret){
if(root.left==null && root.right==null){
ret.add(s);
}
else{
if(root.left!=null) paths(root.left,s+"->"+root.left.val,ret);
if(root.right!=null) paths(root.right,s+"->"+root.right.val,ret);
}
} }

  

运行结果:

(easy)LeetCode  257.Binary Tree Paths

上一篇:oracle导出空表


下一篇:《python核心编程》读书笔记——列表解析