Skip to main content
All Questions

Count the subsets of a binary tree's nodes in which no two chosen nodes are directly connected.

Unlock detailed company stats for this questionUpgrade

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

No answers contributed by the community yet.

Related courses

Course

Software Engineering Interview Prep

Land your dream software engineering role at Google, Amazon, Microsoft, Meta, Apple, and other top companies. Learn from mock interviews, frameworks, and advice from senior candidates—practice data structures, algorithms, system design, people management, behavioral interviews, and more.

Course

System Design Interviews

Learn how to answer the latest system design questions across product, infrastructure, and AI domains. Features in-depth video examples, written breakdowns, and helpful reference patterns. Watch senior engineers and managers answer these questions in mock interview videos.