题目链接:https://leetcode.com/problems/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"]
思路:
难点在于要 路径要作为参数传入
算法:
List<String> strList = new ArrayList<String>();
public List<String> binaryTreePaths(TreeNode root) {
if (root != null) {
findPath(root, String.valueOf(root.val));
}
return strList;
}
public void findPath(TreeNode p, String path) {
if (p.left == null && p.right == null)
strList.add(path);
if (p.left != null)
findPath(p.left, path + "->" + p.left.val);
if (p.right != null)
findPath(p.right, path + "->" + p.right.val);
}