leetcode-cn Daily Challenge on September 4th, 2020.
Difficulty : Easy
Related Topics : Tree、DFS
Given a binary tree, return all root-to-leaf paths.
Note: A leaf is a node with no children.
Input: 1 / \ 2 3 \ 5 Output: ["1->2->5", "1->3"] Explanation: All root-to-leaf paths are: 1->2->5, 1->3
- mine
- Java
Runtime: 9 ms, faster than 47.07%, Memory Usage: 39.6 MB, less than 81.56% of Java online submissions
public List<String> binaryTreePaths(TreeNode root) { List<String> res = new LinkedList<>(); if(root == null) return res; dfs(res, root, String.valueOf(root.val)); return res; } void dfs(List<String> res, TreeNode node, String t){ if(node.left == null && node.right == null){ res.add(t); return; } if(node.left != null){ dfs(res, node.left, t + "->" + node.left.val); } if(node.right != null){ dfs(res, node.right, t + "->" + node.right.val); } }
- Java