Binary Tree Paths
Thoughts
Code
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private void dfs(TreeNode root, String cur, List<String> res) {
if (root.left == null && root.right == null) {
res.add(cur + root.val);
}
if (root.left != null) {
dfs(root.left, cur + root.val + "->", res);
}
if (root.right != null) {
dfs(root.right, cur + root.val + "->", res);
}
}
public List<String> binaryTreePaths(TreeNode root) {
List<String> res = new ArrayList<>();
if (root != null) {
dfs(root, "", res);
}
return res;
}
}Analysis
Ver.2
Last updated