[LeetCode 265] Count Univalue Subtrees

来源:互联网 发布:linux grub无法用命令 编辑:程序博客网 时间:2024/04/29 16:53

题目:

Given a binary tree, count the number of uni-value subtrees.

A Uni-value subtree means all nodes of the subtree have the same value.

For example:
Given binary tree,

              5             / \            1   5           / \   \          5   5   5

return 4.

class Solution {public:int count;int countUnivalSubtrees(TreeNode* root) {if(root==NULL) return 0;count=0;unival(root);return count;}bool unival(TreeNode* root) {bool left=true,right=true;if(root->left) {left=unival(root->left);if(root->val!=root->left->val) left=false;}if(root->right) {right=unival(root->right);if(root->val!=root->right->val) right=false;}if(left&&right) {count++;return true;}return false;}};


0 0