纸上得来终觉浅 绝知此事要躬行

纸上得来终觉浅 绝知此事要躬行

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;
}

02-17 12:33