Find the Root of a Tree from the Sum of Child Node IDs
Last Updated : 12 Dec, 2024
Given a Binary Tree with nodes labelled from 1 to n, where n is the total number of nodes. The task is to identify the root of binary tree given that each node is described by a pair consisting of its id and the sum of its children's id's.
Examples:
Input: [[1, 5], [2, 0], [3, 0], [4, 0], [5, 5], [6, 5]] Output: 6 Explanation: In this question, two trees having 6 as their root node can me generated.
Input: [[4, 0] Output: 4 Explanation: 4 is the only node in a tree and thus does not have any child as well.
Approach:
The idea is to use the property that every node id, except for the root, appears in the sum of children ids. By calculating the total sum of all node id's and subtracting it to the total sum of all children sum, the difference will be the id of the root node.
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.