题目:
给定一个二叉树,返回所有从根节点到叶子节点的路径。
说明: 叶子节点是指没有子节点的节点。
示例:
输入:
1
/ \
2 3
\
5
输出: ["1->2->5", "1->3"]
解释: 所有根节点到叶子节点的路径为: 1->2->5, 1->3
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-paths
思路:
辅助函数
递归
代码如下:
/**
* 二叉树的所有路径
* @param root
* @return
*/
public List<String> binaryTreePaths (TreeNode root) {
List<String> res = new ArrayList<>();
if (root != null) {
helper(root, res, "");
}
return res;
}
/**
* 辅助函数
* @param root
* @param res
* @param path
*/
public void helper (TreeNode root, List<String> res, String path) {
if (root.left == null && root.right == null) {
res.add(path + root);
}
if (root.left != null) {
helper(root.left, res, path + root.val + "->");
}
if (root.right != null) {
helper(root.right, res, path + root.val+ "->");
}
}