LeetCode 250. Count Univalue
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.
Example :
Input: root = [5,1,5,5,5,null,5]
5
/
1 5
/ \
5 5 5
Output: 4
解法1:
因为是premium的题目,我在www.codingninjas.com上做的。
/*************************************************************
Following is the Binary Tree node structure
class BinaryTreeNode
{
public :
T data;
BinaryTreeNode<T> *left;
BinaryTreeNode<T> *right;
BinaryTreeNode(T data) {
this -> data = data;
left = NULL;
right = NULL;
}
};
*************************************************************/
int count = 0;
int helper(BinaryTreeNode<int> *root) {
if (!root) return -100;
if (!root->left && !root->right) {
count++;
return root->data;
}
int left = helper(root->left);
int right = helper(root->right);
if (left != right) {
if (left != -100 && right != -100) return -200;
}
if (left == root->data || right == root->data) {
count++;
return root->data;
}
return -300;
}
int countUnivalTrees(BinaryTreeNode<int> *root)
{
// Write your code here.
count=0; //这行可能不需要,但是codingninjas的环境好像有点问题,每个测试用例都需要清零一下。
helper(root);
return count;
}
本文介绍了一种解决LeetCode250题的方法,计算二叉树中具有相同值的子树的数量。通过递归函数`helper`遍历树节点,如果左右子树的根节点值相等或者子树值不同时返回-200,否则计数加一。
791

被折叠的 条评论
为什么被折叠?



