Given two integers N and X, where N is the number of nodes in an almost complete binary tree. The task is to find:
- The number of nodes that are at X distance from the root.
- The number of nodes that are at X distance from any leaf in its subtree.
Note: A Complete binary tree is a binary tree in which every level, except possibly the last, is completely filled and all nodes are as far left as possible.
Input: N = 6, X = 0 Output: 1 3 Complete Binary Tree of 6 nodes is 1 / \ 2 3 / \ / 4 5 6 Nodes that are at 0 distance from root = 1 (root itself). Nodes that are at 0 distance from any of the leaf = 3 (all the leaves of the tree) Input: N = 13, X = 1 Output: 2 4 Complete Binary Tree of 13 nodes. 1 / \ 2 3 / \ / \ 4 5 6 7 / \ / \ / \ 8 9 10 11 12 13 Nodes that are at 0 distance from root = 2 (node no. 2 and 3) Nodes that are at 0 distance from any of the leaf = 4 (node no. 4, 5, 6 and 3)
- Finding the number of nodes that are x distance away from the root is simple. We simply print the number of nodes at x-th height. We know that in a complete binary tree every level is complete, except possibly the last and all nodes are as far left as possible. So, the height h of a complete binary tree is calculated as floor(log2(n)) where n is the total number of nodes. Also, the number of nodes at i-th height will be 2i and the number of nodes that are at last level (i.e at height h) = 2h – (max_total_nodes – n), where 2h are maximum nodes at height h.
- Finding the number of nodes that are x distance away from any leaf in its subtree is a little bit tricky. It’s about observing the fact that if we have l leaf nodes then, ceil(l/2) nodes are 1 unit distance away from leaves, ceil(l/4) nodes are 2 units distance away from leaves …. till ceil(l/2i) nodes are i units distance away from leaves. We will first find the count of leaf nodes and apply the above method to find nodes that are x distance away from leaf.
Below is the implementation of the above approach:
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.