Skip to content

Commit

Permalink
Create 2265_Count_Nodes_Equal_to_Average_of_Subtree.java
Browse files Browse the repository at this point in the history
  • Loading branch information
mkhuzaima committed Nov 2, 2023
1 parent 9cbdd4f commit dcc12ed
Showing 1 changed file with 47 additions and 0 deletions.
47 changes: 47 additions & 0 deletions 2265_Count_Nodes_Equal_to_Average_of_Subtree.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
// id: 2265
// Name: Count Nodes Equal to Average of Subtree
// link: https://leetcode.com/problems/count-nodes-equal-to-average-of-subtree/
// Difficulty: Medium

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
int count = 0;

int [] tuple = new int[3]; // match in tree, count in tree, sum of node values

public int averageOfSubtree(TreeNode root) {
// count nodes having value = average;
return countNodes(root)[0];
}

private int[] countNodes(TreeNode root) {
if (root == null) return new int[]{0, 0, 0};

int[] left = countNodes(root.left);
int[] right = countNodes(root.right);

int [] result = new int[]{left[0]+right[0], left[1]+right[1]+1, left[2]+right[2]+root.val};

int average = result[2]/result[1];

if (root.val == average) {
result[0]++;
}
return result;
}

}

0 comments on commit dcc12ed

Please sign in to comment.