257. Binary Tree Paths (Easy)
https://leetcode.com/problems/binary-tree-paths/
Given 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
Solutions
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> ans = new ArrayList<>();
if (root == null) {
return ans;
}
dfs(root, ans, "");
return ans;
}
private void dfs(TreeNode root, List<String> paths, String path) {
if (root.left == null && root.right == null) {
paths.add(path + root.val);
return;
}
if (root.left != null) {
dfs(root.left, paths, path + root.val + "->");
}
if (root.right != null) {
dfs(root.right, paths, path + root.val + "->");
}
}
}