Ninja technique🥷 to ACE DSA Interviews.
maxVal
variable to store max value seen so far.maxVal
, increase the count ans update maxVal
variable.class Solution {
private:
int ans = 0;
void preorder(TreeNode* root, int maxVal)
{
if (root == NULL) return;
if (root->val >= maxVal){
ans++;
maxVal = root->val;
}
preorder(root->left, maxVal);
preorder(root->right, maxVal);
}
public:
int goodNodes(TreeNode* root)
{
preorder(root, INT_MIN);
return ans;
}
};