leetcode-binary-tree-paths 发表于 2016-09-07 | 分类于 算法 , leetcode | 题目大意 https://leetcode.com/problems/binary-tree-paths/ 给你一棵二叉树,输出所有root节点到leaf节点的路径。 题目分析 比较简单的递归。 代码12345678910111213141516171819202122232425262728293031323334/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { private List<String> ans; private void helper(TreeNode r, String path, int idx) { if (r == null) { return; } if (!path.equals("")) { path += "->"; } if (r.left == null && r.right == null) { ans.add(path + r.val); return; } helper(r.left, path + r.val, idx + 1); helper(r.right, path + r.val, idx + 1); } public List<String> binaryTreePaths(TreeNode root) { ans = new ArrayList<String>(); helper(root, "", 0); return ans; }}