Given a binary tree with N nodes, in which each node value represents number of candies present at that node, and there are N candies in total. In one move, one may choose two adjacent nodes and move one candy from one node to another (the move may be from parent to child, or from child to parent.)
The task is to find the number of moves required such that every node have exactly one candy.
Input : 3 / \ 0 0 Output : 2 Explanation: From the root of the tree, we move one candy to its left child, and one candy to its right child. Input : 0 / \ 3 0 Output :3 Explanation : From the left child of the root, we move two candies to the root [taking two moves]. Then, we move one candy from the root of the tree to the right child.
The idea is to traverse the tree from leaf to root and consecutively balance all of the nodes. To balance a node, the number of candy at that node must be 1.
There can be two cases:
- If a node needs candies, if the node of the tree has 0 candies (an excess of -1 from what it needs), then we should push a candy from its parent onto the node.
- If the node has more than 1 candy. If it has say, 4 candies (an excess of 3), then we should push 3 candies off the node to its parent.
So, the total number of moves from that leaf to or from its parent is excess = abs(num_candies – 1).
Once a node is balanced, we never have to consider this node again in the rest of our calculation.
Below is the implementation of the above approach:
- Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
- Minimum swap required to convert binary tree to binary search tree
- Check whether a binary tree is a full binary tree or not | Iterative Approach
- Convert a Binary Tree to Threaded binary tree | Set 2 (Efficient)
- Convert a Binary Tree to Threaded binary tree | Set 1 (Using Queue)
- Binary Tree to Binary Search Tree Conversion
- Check whether a given binary tree is skewed binary tree or not?
- Binary Tree to Binary Search Tree Conversion using STL set
- Check if a binary tree is subtree of another binary tree | Set 2
- Check whether a binary tree is a full binary tree or not
- Check if a binary tree is subtree of another binary tree | Set 1
- Given level order traversal of a Binary Tree, check if the Tree is a Min-Heap
- Print Binary Tree levels in sorted order | Set 3 (Tree given as array)
- Convert an arbitrary Binary Tree to a tree that holds Children Sum Property
- Check if a given Binary Tree is height balanced like a Red-Black Tree
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : prerna saini