-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCount Nodes Equals Leetcode 2265
81 lines (61 loc) · 1.55 KB
/
Count Nodes Equals Leetcode 2265
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
// This is Brute Force solution
// TC - O(N*N)
// SC - O(N)
class Solution {
private int count ;
private int sum ;
public int averageOfSubtree(TreeNode root) {
Queue<TreeNode> q = new LinkedList();
q.offer(root);
int ans = 0;
while (!q.isEmpty()) {
TreeNode current = q.poll();
count = 0;
sum = 0;
helper(current) ;
if ((sum/count) == current.val) {
ans++;
}
if (current.left != null) {
q.offer(current.left);
}
if (current.right != null) {
q.offer(current.right);
}
}
return ans;
}
private void helper(TreeNode root) {
if (root == null) {
return;
}
helper(root.left);
helper(root.right);
sum += root.val;
count++;
}
}
// This is a optimized version of this the question
// TC - O(N)
// SC - (N) stack space
class Solution {
private int ans ;
public int averageOfSubtree(TreeNode root) {
ans = 0;
helper(root);
return ans;
}
private int[] helper(TreeNode root) {
if (root == null) {
return new int[]{0, 0};
}
int[] left = helper(root.left);
int[] right = helper(root.right);
int count = 1 + left[0] + right[0];
int sum = root.val + left[1] + right[1];
if ((sum/count) == root.val) {
ans++;
}
return new int[]{count, sum};
}
}