Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Definition for a binary tree node.
- * 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 {
- int ans = 0;
- public:
- int countUnivalSubtrees(TreeNode* root) {
- dfs(root);
- return ans;
- }
- bool dfs(TreeNode* root){
- if(!root) return true;
- if(!root->left && !root->right){
- ans++;
- return true;
- }
- bool sameVal = true;
- if(root->left){
- sameVal &= dfs(root->left) && (root->val == root->left->val);
- }
- if(root->right){
- sameVal &= dfs(root->right) && (root->val == root->right->val);
- }
- if(!sameVal) return false;
- ans++;
- return true;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement