250. Count Univalue Subtrees
Given the root of a binary tree, return the number of uni-value subtrees.
A uni-value subtree means all nodes of the subtree have the same value.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
|
class Solution { int ans = 0; bool eq(TreeNode* root) { if(!root) return false; else if(!root->left and !root->right) { ans++; return true; } else if(root->left and root->right) { bool res = true; res &= eq(root->left); res &= eq(root->right); if(!res) return false; if(root->val == root->left->val and root->val == root->right->val) { ans++; return true; } return false; } else if(root->left) { bool res = eq(root->left); if(!res) return false; if(res && root->left->val == root->val) { ans++; return true; } return false; } else { bool res = eq(root->right); if(!res) return false; if(res && root->right->val == root->val) { ans++; return true; } return false; } } public: int countUnivalSubtrees(TreeNode* root) { eq(root); return ans; } };
|