[LintCode] Binary Tree Paths - Road to Glory
Problem
Given a binary tree, return all root-to-leaf paths.
Example
Given the following binary tree:
1 / \2 3 \ 5
All root-to-leaf paths are:
[ "1->2->5", "1->3"]
Solution
public class Solution { public List<String> binaryTreePaths(TreeNode root) { // Write your code here List<String> res = new ArrayList<String>(); if (root == null) {return res; } findpaths(root, res, root.val + "");//这里+""巧妙地调用了String return res; } public void findpaths(TreeNode root, List<String> res, String cur) { if (root.left != null) { findpaths(root.left, res, cur + "->" + root.left.val); } if (root.right != null) { findpaths(root.right, res, cur + "->" + root.right.val); } if (root.left == null && root.right == null) { res.add(cur); return; } }}