Find a tree with the given values and print the edges of the tree. Print “-1”, if the tree is not possible.
Given three integers n, d and h.
n -> Number of vertices. [1, n] d -> Diameter of the tree (largest distance between two vertices). h -> Height of the tree (longest distance between vertex 1 and another vertex)
Input : n = 5, d = 3, h = 2 Output : 1 2 2 3 1 4 1 5 Explanation : We can see that the height of the tree is 2 (1 -> 2 --> 5) and diameter is 3 ( 3 -> 2 -> 1 -> 5). So our conditions are satisfied. Input : n = 8, d = 4, h = 2 Output : 1 2 2 3 1 4 4 5 1 6 1 7 1 8 Explanation :
- Observe that when d = 1, we cannot construct a tree (if tree has more than 2 vertices). Also when d > 2*h, we cannot construct a tree.
- As we know that height is the longest path from vertex 1 to another vertex. So build that path from vertex 1 by adding edges up to h. Now, if d > h, we should add another path to satisfy diameter from vertex 1, with a length of d – h.
- Our conditions for height and diameter are satisfied. But still some vertices may be left. Add the remaining vertices at any vertex other than the end points. This step will not alter our diameter and height. Chose vertex 1 to add the remaining vertices (you can chose any).
- But when d == h, choose vertex 2 to add the remaining vertices.
1 2 2 3 1 4 1 5
- 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
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.