This problem was asked by Google.
A unival tree (which stands for “universal value”) is a tree where all nodes under it have the same value.
Given the root to a binary tree, count the number of unival subtrees.
For example, the following tree has 5 unival subtrees:
采用bottom-up的递归方法。
Time complexity of this solution is O(n) where n is number of nodes in given binary tree.
Auxiliary Space: O(h) where h is the height of the tree due to recursion call.
#include<bits/stdc++.h>
using namespace std;
// A Tree node
struct Node
{
int data;
struct Node* left, *right;
};
// Utility function to create a new node
Node* newNode(int data)
{
Node* temp = new Node;
temp->data = data<