257. All paths to a binary tree

Difficulty: easy

Given a binary tree, return all paths from the root node to the leaf node.

Note: Leaf nodes are nodes that have no child nodes.

Example:

Input: 1, 2, 3, 5 / output: [" 1 - > 2 - > 5 ", "1 - > 3"] : all the path of the root node to leaf node as follows: 1 - > 2 - > 5, 1 - > 3Copy the code

Solution

Language: java

/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { List<String> res = new ArrayList(); public List<String> binaryTreePaths(TreeNode root) { if(root == null) return res; dfs(root , ""); return res; Void DFS (TreeNode node, String path) {if(node == null) return; StringBuffer sb = new StringBuffer(path); sb.append(node.val); if(node.left == null && node.right == null) { res.add(sb.toString()); return; } // if it is not a leaf node sb. Append ("->"); dfs(node.left , sb.toString()); dfs(node.right , sb.toString()); }}Copy the code