FastPrepCount One-Valued Regions in a Binary Tree

Count One-Valued Regions in a Binary Tree

Google logoGoogle● EasyINTERNNEW GRADPHONE SCREENONSITE INTERVIEW
Learn

Problem statement

Given the root of a binary tree whose node values are only 0 or 1, return the number of connected regions formed by nodes with value 1.

Two value-1 nodes belong to the same region when one can reach the other by following parent-child edges through only value-1 nodes.

An empty tree contains zero regions.

Function

countOneRegions(root: TreeNode) → int

Examples

Example 1

root = [1,1,0,1,0,1,1]return = 3

The root and the value-1 nodes in its left subtree form one region. The two value-1 children beneath the value-0 right child each start a separate region.

Example 2

root = [0,1,1]return = 2

The two value-1 children are separated by their value-0 parent, so they belong to different regions.

Example 3

root = []return = 0

An empty tree contains no value-1 regions.

Constraints

  • The tree contains at most 100000 nodes.
  • Every node value is either 0 or 1.

More Google problems

See Google hiring insights
public int countOneRegions(TreeNode root) {
  // Write your code here.
}
root[1,1,0,1,0,1,1]
expected3
Checking account…