15. Count Univalue Subtrees

250. Count Univalue Subtreesarrow-up-right

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.

Example :

Input:  root = [5,1,5,5,5,null,5]

              5
             / \
            1   5
           / \   \
          5   5   5

Output: 4

方法一

遞迴時間複雜度計算 this runs in O(n^2) time. For each node of the tree, we’re evaluating each node in its subtree again as well.

def count_unival_subtrees(root):
  if root is None:
    return 1
  left = count_unival_subtrees(root.left)
  right = count_unival_subtrees(root.right)

  return 1 + left + right if is_unival(root) else left + right

def is_unival(root):
  return unival_helper(root, root.value)

def unival_helper(root, value):
   if root is None:
        return True
   if root.value == value:
        return unival_helper(root.left, value) and unival_helper(root.right, value)
   return False

方法二

利用cache計算過的東西不在重複計算

Last updated