|
1 | 1 | package g1001_1100.s1022_sum_of_root_to_leaf_binary_numbers; |
2 | 2 |
|
3 | | -// #Easy #Depth_First_Search #Tree #Binary_Tree #2022_02_26_Time_3_ms_(28.58%)_Space_43.6_MB_(5.47%) |
| 3 | +// #Easy #Depth_First_Search #Tree #Binary_Tree |
| 4 | +// #2025_05_03_Time_0_ms_(100.00%)_Space_42.08_MB_(64.36%) |
4 | 5 |
|
5 | 6 | import com_github_leetcode.TreeNode; |
6 | | -import java.util.ArrayList; |
7 | | -import java.util.List; |
8 | 7 |
|
9 | 8 | /* |
10 | 9 | * Definition for a binary tree node. |
|
23 | 22 | */ |
24 | 23 | public class Solution { |
25 | 24 | public int sumRootToLeaf(TreeNode root) { |
26 | | - List<List<Integer>> paths = new ArrayList<>(); |
27 | | - dfs(root, paths, new ArrayList<>()); |
28 | | - int sum = 0; |
29 | | - for (List<Integer> list : paths) { |
30 | | - int num = 0; |
31 | | - for (int i : list) { |
32 | | - num = (num << 1) + i; |
33 | | - } |
34 | | - sum += num; |
35 | | - } |
36 | | - return sum; |
| 25 | + return sumRootToLeaf(root, 0); |
37 | 26 | } |
38 | 27 |
|
39 | | - private void dfs(TreeNode root, List<List<Integer>> paths, List<Integer> path) { |
40 | | - path.add(root.val); |
41 | | - if (root.left != null) { |
42 | | - dfs(root.left, paths, path); |
43 | | - path.remove(path.size() - 1); |
44 | | - } |
45 | | - if (root.right != null) { |
46 | | - dfs(root.right, paths, path); |
47 | | - path.remove(path.size() - 1); |
| 28 | + private int sumRootToLeaf(TreeNode root, int sum) { |
| 29 | + if (root == null) { |
| 30 | + return 0; |
48 | 31 | } |
| 32 | + sum = 2 * sum + root.val; |
49 | 33 | if (root.left == null && root.right == null) { |
50 | | - paths.add(new ArrayList<>(path)); |
| 34 | + return sum; |
51 | 35 | } |
| 36 | + return sumRootToLeaf(root.left, sum) + sumRootToLeaf(root.right, sum); |
52 | 37 | } |
53 | 38 | } |
0 commit comments