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.
1public class TreeNode {
2 public int val;
3 public TreeNode left;
4 public TreeNode right;
5 public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
6 this.val = val;
7 this.left = left;
8 this.right = right;
9 }
10}
11
12public class Solution {
13 private int Dfs(TreeNode node, int maxVal) {
14 if (node == null) return 0;
15 int good = (node.val >= maxVal) ? 1 : 0;
16 maxVal = Math.Max(maxVal, node.val);
17 good += Dfs(node.left, maxVal);
18 good += Dfs(node.right, maxVal);
19 return good;
20 }
21
22 public int GoodNodes(TreeNode root) {
23 return Dfs(root, root.val);
24 }
25}
26
This C# implementation defines a private recursive method Dfs
that is called from the public method GoodNodes
. It counts the nodes that are considered good.
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.
#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.