原题: https://leetcode-cn.com/problems/binary-tree-paths/
给定一个二叉树,返回所有从根节点到叶子节点的路径。
说明: 叶子节点是指没有子节点的节点。
示例:
输入:
1
/ \
2 3
\
5输出: ["1->2->5", "1->3"]
解释: 所有根节点到叶子节点的路径为: 1->2->5, 1->3
package com.leetcode.test.tree; import com.sun.org.apache.regexp.internal.RE; import java.util.ArrayList; import java.util.List; public class Solution8 { public static void main(String[] args) { TreeNode a1 = new TreeNode(1); TreeNode a2 = new TreeNode(2); TreeNode a3 = new TreeNode(3); TreeNode a4 = new TreeNode(5); a1.left = a2; a1.right = a3; a2.right = a4; System.out.println(binaryTreePaths(a1)); } public static List<String> binaryTreePaths(TreeNode root) { List<String> list = new ArrayList(); binaryTreePath(root, "", list); return list; } public static void binaryTreePath(TreeNode root, String s, List list) { if (root.left != null) { //如果存在左节点, 则将当前节点的值拼接起来,然后传递给左节点 binaryTreePath(root.left, s + "->" + root.val, list); } if (root.right != null) { //存在右节点, 则将当前节点的值拼接起来,然后传递给右节点 binaryTreePath(root.right, s + "->" + root.val, list); } if (root.left == null && root.right == null) { //叶子节点 s += "->" + root.val; list.add(s.substring(2)); } } }