Advertisement
jayati

Count Good Nodes in Binary Tree

May 8th, 2024
524
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.64 KB | None | 0 0
  1. /**
  2.  * Definition for a binary tree node.
  3.  * struct TreeNode {
  4.  *     int val;
  5.  *     TreeNode *left;
  6.  *     TreeNode *right;
  7.  *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
  8.  *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
  9.  *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
  10.  * };
  11.  */
  12. class Solution {
  13. public:
  14.     int goodNodes(TreeNode* root,int mx=INT_MIN) {
  15.  
  16.         if(!root)
  17.         {
  18.             return 0;
  19.         }
  20.  
  21.         return (mx<=root->val?1:0)+goodNodes(root->left,max(root->val,mx))+goodNodes(root->right,max(root->val,mx));
  22.        
  23.     }
  24. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement