Description:
Consider here 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 sum of children ids.
So the idea is that every node id appears in children sum except root. So if we do sum of all ids and subtract it from sum of all children sums, we get root.
Program:
'''Find root of tree where children
sum for every node id is given'''
def findRoot(arr, n) :
root = 0
for i in range(n):
root += (arr[i][0]-arr[i][1])
return root
if __name__ == '__main__':
arr = [[1, 5], [2, 0],
[3, 0], [4, 0],
[5, 5], [6, 5]]
n = len(arr)
print(findRoot(arr, n))
Output:
6
>>>
Comments