LeetCode 2265: Count Nodes Equal to Average of Subtree Solution
Master LeetCode problem 2265 (Count Nodes Equal to Average of Subtree), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
2265. Count Nodes Equal to Average of Subtree
Problem Explanation
Explanation:
To solve this problem, we can perform a depth-first search (DFS) on the binary tree. For each node, we will recursively calculate the sum and count of nodes in its subtree. With this information, we can determine the average of the subtree and compare it with the node's value. If they are equal, we increment a counter.
Algorithm:
- Implement a recursive function that calculates the sum and count of nodes in the subtree rooted at a given node.
- Perform a DFS on the binary tree and at each node:
- Calculate the sum and count of nodes in its subtree.
- Check if the node's value is equal to the average of the subtree.
- Increment the counter if they are equal.
- Return the total count of nodes where the value is equal to the average of the subtree.
Time Complexity:
The time complexity of this approach is O(n), where n is the number of nodes in the binary tree. This is because we visit each node exactly once during the DFS traversal.
Space Complexity:
The space complexity is O(h), where h is the height of the binary tree. This is due to the recursive stack space used during the DFS traversal. :
Solution Code
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
class Solution {
public int countEqualAverage(TreeNode root) {
return dfs(root)[0];
}
private int[] dfs(TreeNode node) {
if (node == null) {
return new int[]{0, 0};
}
int[] left = dfs(node.left);
int[] right = dfs(node.right);
int sum = left[1] + right[1] + node.val;
int count = left[0] + right[0] + 1;
int total = (node.val * count == sum) ? 1 : 0;
return new int[]{total + left[0] + right[0], sum};
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 2265 (Count Nodes Equal to Average of Subtree)?
This page provides optimized solutions for LeetCode problem 2265 (Count Nodes Equal to Average of Subtree) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 2265 (Count Nodes Equal to Average of Subtree)?
The time complexity for LeetCode 2265 (Count Nodes Equal to Average of Subtree) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2265 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2265 in Java, C++, or Python.