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"]
public class Solution { public List<String> binaryTreePaths(TreeNode root) { List<String> res = new ArrayList<>(); if (root != null) { paths(res, "", root); } return res; } public void paths(List<String> res, String path, TreeNode root) { if (root.left == null && root.right == null) { res.add(path + root.val); return; } if (root.left != null) { paths(res, path + root.val + "->", root.left); } if (root.right != null) { paths(res, path + root.val + "->" , root.right); } } }
从下往上:
public class Solution { public List<String> binaryTreePaths(TreeNode root) { List<String> res = new ArrayList<>(); if (root == null) { return res; } if (root.left == null && root.right == null) { res.add(root.val + ""); return res; } for (String path : binaryTreePaths(root.left)) { res.add(root.val + "->" + path); } for (String path : binaryTreePaths(root.right)) { res.add(root.val + "->" + path); } return res; } }
这个方法是每次都新建一个list,然后对返回的所有list前面加上root的值,思路很简单,但这个实现之前没见过。。。
再次遇到也不知道能不能写出来。。。需要回顾。
原文:http://www.cnblogs.com/aprilyang/p/6357418.html