给定一个二叉树,返回所有从根节点到叶子节点的路径。
说明: 叶子节点是指没有子节点的节点。
示例:
输入:
1
/ \
2 3
\
5
输出: ["1->2->5", "1->3"]
解释: 所有根节点到叶子节点的路径为: 1->2->5, 1->3
class Solution {
ArrayList pathList = new ArrayList();
public List<String> binaryTreePaths(TreeNode root) {
if (root == null) return pathList;
preOrder(root, "");
return pathList;
}
private void preOrder(TreeNode root, String path) {
path += root.val;
if (root.left == null && root.right == null) pathList.add(path);
else {
path += "->";
if (root.left != null) preOrder(root.left, path);
if (root.right != null) preOrder(root.right, path);
}
}
}