Count One-Valued Regions in a Binary Tree
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) → intExamples
Example 1
root = [1,1,0,1,0,1,1]return = 3The 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 = 2The two value-1 children are separated by their value-0 parent, so they belong to different regions.
Example 3
root = []return = 0An empty tree contains no value-1 regions.
Constraints
- The tree contains at most
100000nodes. - Every node value is either
0or1.