Advertisement
nikunjsoni

250

May 7th, 2021
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.00 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 countUnivalSubtrees(TreeNode* root) {
  16.         dfs(root);
  17.         return ans;
  18.     }
  19.    
  20.     bool dfs(TreeNode* root){
  21.         if(!root) return true;
  22.         if(!root->left && !root->right){
  23.             ans++;
  24.             return true;
  25.         }
  26.         bool sameVal = true;
  27.         if(root->left){
  28.             sameVal &= dfs(root->left) && (root->val == root->left->val);
  29.         }
  30.         if(root->right){
  31.             sameVal &= dfs(root->right) && (root->val == root->right->val);
  32.         }
  33.        
  34.         if(!sameVal) return false;
  35.         ans++;
  36.         return true;
  37.     }
  38. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement