Given N and K, print a tree such that the tree has no more than K leaf nodes and every other node has at least two nodes connected to it. The task is to build a tree of N nodes exactly in such a way that the distance between the farthest leaf nodes is minimized. Print the minimized distance also.
Note: There can be multiple trees.
Input: N = 5, K = 3
Output: Distance = 3
The tree is:
Input: N = 3, K = 2
Output: Distance = 2
The tree is:
- Initially, the tree will have k-1 nodes connected to 1.
- Then connect one node to all the k-1 nodes one by one.
- If nodes are left, keep connecting them to the leaf nodes one by one.
The diagrammatic representation of how to build the tree will make things more clear. In the image below, K = 6 and for any number N has been demonstrated. The nodes in yellow are the leaf nodes.
Below is the implementation of the above approach:
Distance = 3 The tree is: 1 2 1 3 4 1 5 2
- Farthest distance of a Node from each Node of a Tree
- Minimum value of distance of farthest node in a Graph
- Count of nodes which are at a distance X from root and leaves
- Partition a set into two subsets such that difference between max of one and min of other is minimized
- Find farthest node from each node in Tree
- Print all nodes in a binary tree having K leaves
- Assign weights to edges such that longest path in terms of weights is minimized
- Choose an integer K such that maximum of the xor values of K with all Array elements is minimized
- Find distance between two nodes of a Binary Tree
- Queries to find distance between two nodes of a Binary tree
- Queries to find distance between two nodes of a Binary tree - O(logn) method
- Shortest distance between two nodes in an infinite binary tree
- Distance between two nodes of binary tree with node values from 1 to N
- Find distance between two nodes in the given Binary tree for Q queries
- Count the nodes of the tree which make a pangram when concatenated with the sub-tree nodes
- Find the maximum path sum between two leaves of a binary tree
- Minimum sum path between two leaves of a binary tree
- Common nodes in the inorder sequence of a tree between given two nodes in O(1) space
- Count of all prime weight nodes between given nodes in the given Tree
- Minimum distance to visit all the nodes of an undirected weighted 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 firstname.lastname@example.org. 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.