Subtree Node Count Problem
We are provided with a tree containing 'N' nodes, numbered from 0 to N-1. The objective is to determine the total number of nodes within each subtree of the provided tree. Specifically, for each node in a general tree, calculate the count of elements in the subtrees rooted at each node.
Input:
T # Number of test cases
For each test case:
N # Number of nodes in the tree
N-1 lines containing two integers U and V indicating an edge between node U and node V
Output:
For each test case, output the number of elements in all subtrees of the tree, in any order.
Example:
Consider an image representation of the tree for clarity.
Constraints:
1 ≤ T ≤ 100
1 ≤ N, E ≤ 104
0 ≤ U,V < N
- Time Limit: 1 second
Note:
1. The tree will always have its root at node 0.
2. Answers can be presented in any sequence.
3. A node that is a leaf will have a subtree size of 1 (only the node itself).

AnswerBot
4mo
Given a tree with N nodes, find the number of elements in each subtree rooted at every node.
Traverse the tree using Depth First Search (DFS) to calculate subtree sizes for each node.
Use an array to st...read more
Help your peers!
Add answer anonymously...
ThoughtWorks Software Developer interview questions & answers
A Software Developer was asked Q. How would you add an API to the existing repository?
A Software Developer was asked Q. In a code pairing round, you will be given a story where you need to add an API ...read more
A Software Developer was asked Q. What is the difference between CHAR and VARCHAR2 data types in SQL?
Popular interview questions of Software Developer
A Software Developer was asked Q1. How would you add an API to the existing repository?
A Software Developer was asked Q2. In a code pairing round, you will be given a story where you need to add an API ...read more
A Software Developer was asked Q3. What is the difference between CHAR and VARCHAR2 data types in SQL?
>
ThoughtWorks Software Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app


Trusted by over 1.5 Crore job seekers to find their right fit company
80 L+
Reviews
10L+
Interviews
4 Cr+
Salaries
1.5 Cr+
Users
Contribute to help millions
AmbitionBox Awards
Get AmbitionBox app

