Sponsored
Sponsored
Time Complexity: O(n), where n is the number of nodes in the binary tree.
Space Complexity: O(h), where h is the height of the tree due to the recursion stack.
1#include <stdlib.h>
2#include <stdio.h>
3
4struct TreeNode {
5 int val;
6 struct TreeNode *left;
7 struct TreeNode *right;
8};
9
10int dfs(struct TreeNode* node, int maxVal) {
11 if (!node) return 0;
12 int total = 0;
13 if (node->val >= maxVal) total = 1;
14 maxVal = (node->val > maxVal) ? node->val : maxVal;
15 total += dfs(node->left, maxVal);
16 total += dfs(node->right, maxVal);
17 return total;
18}
19
20int goodNodes(struct TreeNode* root) {
21 if (!root) return 0;
22 return dfs(root, root->val);
23}
24
This solution defines a helper function dfs
that performs the depth-first search. It takes parameters for the current node and the maximum value encountered so far. It returns the total count of good nodes.
Time Complexity: O(n), where n is the number of nodes in the tree.
Space Complexity: O(w), where w is the maximum width of the tree.
1#include <queue>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
class Solution {
public:
int goodNodes(TreeNode* root) {
if (!root) return 0;
queue<pair<TreeNode*, int>> q;
q.push({root, root->val});
int goodNodesCount = 0;
while (!q.empty()) {
auto [node, maxVal] = q.front(); q.pop();
if (node->val >= maxVal) goodNodesCount++;
if (node->left) q.push({node->left, max(maxVal, node->val)});
if (node->right) q.push({node->right, max(maxVal, node->val)});
}
return goodNodesCount;
}
};
The C++ solution involves an iterative BFS approach, using the STL queue to traverse nodes level by level, and checking each node's value to update the good nodes count when necessary.