Open In App
Related Articles

Find root of the tree where children id sum for every node is given

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

Consider a binary tree whose nodes have ids from 1 to n where n is the number of nodes in the tree. The tree is given as a collection of n pairs, where every pair represents node id and the sum of children ids.

Examples: 

Input : 1 5
        2 0
        3 0
        4 0
        5 5
        6 5
Output: 6
Explanation: In this case, two trees can 
be made as follows and 6 is the root node.
   6          6
   \         / \
    5       1   4
   / \       \
  1   4       5
 / \         / \
2   3       2   3

Input : 4 0
Output: 4
Explanation: Clearly 4 does 
not have any children and is the
only node i.e., the root node.

At first sight, this question appears to be a typical question of a tree data structure but it 
can be solved as follows.

Every node id appears in children sum except root. So if we do the sum of all ids and subtract it from the sum of all children’s sums, we get the root.

Implementation:

C++


                    

Java


                    

Python3


                    

C#


                    

Javascript


                    

Output
6

Time Complexity: O(n), Where n is the length of the given array.
Auxiliary Space: O(1), As no extra space is used.

 



Last Updated : 29 Jul, 2022
Like Article
Save Article
Share your thoughts in the comments
Similar Reads