-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create 2265_Count_Nodes_Equal_to_Average_of_Subtree.java
- Loading branch information
Showing
1 changed file
with
47 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
|
||
} |