257. Binary Tree Paths
EasyGiven a binary tree, return all root-to-leaf paths.
Note: A leaf is a node with no children.
Example:
Input: 1 / \ 2 3 \ 5 Output: ["1->2->5", "1->3"] Explanation: All root-to-leaf paths are: 1->2->5, 1->3
package leetcode.easy; /** * Definition for a binary tree node. public class TreeNode { int val; TreeNode * left; TreeNode right; TreeNode(int x) { val = x; } } */ public class BinaryTreePaths { java.util.List<String> list = new java.util.LinkedList<>(); public java.util.List<String> binaryTreePaths(TreeNode root) { path(root, ""); return list; } private void path(TreeNode root, String str) { if (null == root) { return; } str = str + "->" + root.val; if (null == root.left && null == root.right) { list.add(str.substring(2)); return; } path(root.left, str); path(root.right, str); } @org.junit.Test public void test() { TreeNode node11 = new TreeNode(1); TreeNode node21 = new TreeNode(2); TreeNode node22 = new TreeNode(3); TreeNode node32 = new TreeNode(5); node11.left = node21; node11.right = node22; node21.left = null; node21.right = node32; node22.left = null; node22.right = null; node32.left = null; node32.right = null; System.out.println(binaryTreePaths(node11)); } }