nikunjsoni

1448

Apr 22nd, 2021
148
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.72 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. int ans=0;
  14. public:
  15.     int goodNodes(TreeNode* root) {
  16.         dfs(root, INT_MIN);
  17.         return ans;
  18.     }
  19.    
  20.     void dfs(TreeNode* curr, int maxSoFar){
  21.         if(!curr) return;
  22.         if(maxSoFar <= curr->val) ans++;
  23.         dfs(curr->left, max(maxSoFar, curr->val));
  24.         dfs(curr->right, max(maxSoFar, curr->val));
  25.     }
  26. };
Advertisement
Add Comment
Please, Sign In to add comment