In a binary tree, a node is considered "good" if the value of the node is greater than or equal to the maximum value encountered on the path from the root to that node. Your task is to find the number of good nodes in the binary tree.
We will use a Depth-First Search (DFS) approach to traverse the tree and calculate the number of good nodes.
Parameters:
node
: Current node in the tree.max_val
: The maximum value encountered along the path from the root to the current node.Base Case:
null
, return 0
since no node exists.Processing Current Node:
max_val
, it is a good node.Recursive Call:
max_val
with the maximum value between max_val
and the current node's value.Return the Total Count:
Input:
8
/
5 9
/ \
4 7 10
/
6 15
Output:
7
Explanation:
The good nodes are 8, 9, 10, 6, and 15, since their values are greater than or equal to the maximum encountered along the path from root.
O(N)
where N
is the number of nodes in the tree, because we visit each node once.O(H)
where H
is the height of the tree. This is the space used by the recursive stack in the DFS traversal.https://leetcode.com/problems/count-the-number-of-good-nodes/description/
Loading component...
Loading component...
Main Function is not defined.
public static int countGoodNodes(vector<vector<int>>& edges) {
int n = edges.size() + 1;
adj.resize(n);
for (const auto& edge : edges) {
int u = edge[0], v = edge[1];
adj[u].push_back(v);
adj[v].push_back(u);
}
ans = 0;
dfs(0, -1);
return ans;
vector<vector<int>> adj;
int ans;
int dfs(int node, int parent) {
int totalNodes = 0;
bool isGood = true;
int subtreeSize = -1;
for (int neighbor : adj[node]) {
if (neighbor == parent){
continue;
}
int currentSize = dfs(neighbor, node);
if (subtreeSize == -1) {
subtreeSize = currentSize;
}
else {
if (currentSize != subtreeSize) {
isGood = false;
}
}
totalNodes += currentSize;
}
if (isGood){
ans++;
}
return totalNodes + 1;
}//function end