|
52 | 52 |
|
53 | 53 | */
|
54 | 54 | public class _663 {
|
55 |
| - /** |
56 |
| - * The idea is that we use a map to store the sum of each node, then in the end, |
57 |
| - * we check if any node has a sum that is exactly half of total sum. |
58 |
| - */ |
59 |
| - public boolean checkEqualTree(TreeNode root) { |
60 |
| - Map<TreeNode, Integer> map = new HashMap<>(); |
61 |
| - int totalSum = sumForEachNode(root, map); |
62 |
| - if (totalSum % 2 != 0 || map.size() < 2) { |
63 |
| - return false; |
64 |
| - } |
65 |
| - for (TreeNode key : map.keySet()) { |
66 |
| - if (map.get(key) == totalSum / 2) { |
67 |
| - return true; |
| 55 | + public static class Solution1 { |
| 56 | + /** |
| 57 | + * The idea is that we use a map to store the sum of each node, then in the end, |
| 58 | + * we check if any node has a sum that is exactly half of total sum. |
| 59 | + */ |
| 60 | + public boolean checkEqualTree(TreeNode root) { |
| 61 | + Map<TreeNode, Integer> map = new HashMap<>(); |
| 62 | + int totalSum = sumForEachNode(root, map); |
| 63 | + if (totalSum % 2 != 0 || map.size() < 2) { |
| 64 | + return false; |
| 65 | + } |
| 66 | + for (TreeNode key : map.keySet()) { |
| 67 | + if (map.get(key) == totalSum / 2) { |
| 68 | + return true; |
| 69 | + } |
68 | 70 | }
|
| 71 | + return false; |
69 | 72 | }
|
70 |
| - return false; |
71 |
| - } |
72 | 73 |
|
73 |
| - private int sumForEachNode(TreeNode root, Map<TreeNode, Integer> map) { |
74 |
| - if (root == null) { |
75 |
| - return 0; |
76 |
| - } |
77 |
| - if (root.left == null && root.right == null) { |
78 |
| - map.put(root, root.val); |
79 |
| - return root.val; |
80 |
| - } |
81 |
| - int leftVal = 0; |
82 |
| - if (root.left != null) { |
83 |
| - leftVal = sumForEachNode(root.left, map); |
84 |
| - } |
85 |
| - int rightVal = 0; |
86 |
| - if (root.right != null) { |
87 |
| - rightVal = sumForEachNode(root.right, map); |
| 74 | + private int sumForEachNode(TreeNode root, Map<TreeNode, Integer> map) { |
| 75 | + if (root == null) { |
| 76 | + return 0; |
| 77 | + } |
| 78 | + if (root.left == null && root.right == null) { |
| 79 | + map.put(root, root.val); |
| 80 | + return root.val; |
| 81 | + } |
| 82 | + int leftVal = 0; |
| 83 | + if (root.left != null) { |
| 84 | + leftVal = sumForEachNode(root.left, map); |
| 85 | + } |
| 86 | + int rightVal = 0; |
| 87 | + if (root.right != null) { |
| 88 | + rightVal = sumForEachNode(root.right, map); |
| 89 | + } |
| 90 | + int val = root.val + leftVal + rightVal; |
| 91 | + map.put(root, val); |
| 92 | + return val; |
88 | 93 | }
|
89 |
| - int val = root.val + leftVal + rightVal; |
90 |
| - map.put(root, val); |
91 |
| - return val; |
92 | 94 | }
|
93 | 95 | }
|
0 commit comments