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.
1class TreeNode:
2 def __init__(self, val=0, left=None, right=None):
3 self.val = val
4 self.left = left
5 self.right = right
6
7class Solution:
8 def dfs(self, node, maxVal):
9 if not node:
10 return 0
11 good = 1 if node.val >= maxVal else 0
12 maxVal = max(maxVal, node.val)
13 return good + self.dfs(node.left, maxVal) + self.dfs(node.right, maxVal)
14
15 def goodNodes(self, root):
16 return self.dfs(root, root.val)
17
This Python solution utilizes a helper function dfs
within the class Solution
. It employs recursion to traverse the tree and count the good nodes as per the conditions provided.
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.