Count the subsets of a binary tree's nodes in which no two chosen nodes are directly connected.
You are given a binary tree containing N nodes. A subset of nodes is called valid if no two selected nodes are directly connected by an edge. Determine the total number of valid subsets that can be formed. The empty subset is also considered valid.
Input: the binary tree as a collection of nodes, where each node contains an integer value and a pointer/reference to its left child and right child. You may assume the structure is a valid binary tree.
Output: the total number of valid subsets, modulo 10^9 + 7.
Example: node 1 is the root, 1->left=2, 1->right=3, 2->left=4, 2->right=5. Some valid subsets: {}, {1}, {2}, {3}, {4}, {5}, {1,4}, {1,5}, {2,3}, {3,4}, {3,5}, {3,4,5}. {1,2} is invalid because nodes 1 and 2 are directly connected; {2,4} is invalid because nodes 2 and 4 are directly connected.
Constraints: 1 <= N <= 2 x 10^5; the answer can be very large, so return it modulo 10^9 + 7.
Format · Technical interview.
Community answers
Related questions
Print the cousins of a given node in a binary tree.Find the first common ancestor of two nodes in a binary tree.Count all leaf nodes in a binary tree.Related courses


