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.
1using System.Collections.Generic;
public class TreeNode {
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
this.val = val;
this.left = left;
this.right = right;
}
}
public class Solution {
public int GoodNodes(TreeNode root) {
if (root == null) return 0;
Queue<(TreeNode, int)> queue = new Queue<(TreeNode, int)>();
queue.Enqueue((root, root.val));
int goodCount = 0;
while (queue.Count > 0) {
(TreeNode node, int maxVal) = queue.Dequeue();
if (node.val >= maxVal) goodCount++;
if (node.left != null) queue.Enqueue((node.left, Math.Max(maxVal, node.val)));
if (node.right != null) queue.Enqueue((node.right, Math.Max(maxVal, node.val)));
}
return goodCount;
}
}
In this C# solution, a queue is used to implement BFS, with each item being a tuple that contains both the current node and the maximum value encountered so far. The process checks each node, updating the count of good nodes as necessary.