Consider a binary tree whose nodes have ids from 1 to n where n is 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.
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 tree data structure but it
can be solved as follows.
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.
This article is contributed by Sunidhi Chaudhary. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Tree Traversals (Inorder, Preorder and Postorder)
- Find the node with minimum value in a Binary Search Tree
- Write a program to Calculate Size of a tree | Recursion
- Write a Program to Find the Maximum Depth or Height of a Tree
- Write a program to Delete a Tree
- If you are given two traversal sequences, can you construct the binary tree?
- Convert a Binary Tree into its Mirror Tree
- Given a binary tree, print out all of its root-to-leaf paths one per line.
- Lowest Common Ancestor in a Binary Search Tree.
- The Great Tree-List Recursion Problem.
- Check sum of Covered and Uncovered nodes of Binary Tree
- Level Order Tree Traversal
- Program to count leaf nodes in a binary tree
- A program to check if a binary tree is BST or not
- Check for Children Sum Property in a Binary Tree