Given the edges of a tree and a sum S. The task is to assign weights to the all the edges of the tree such that the longest path in terms of weights is minimized and the total sum of weights assigned should be S and print the longest path’s weight.
Note: Edges can be assigned any weights in range [0, S] and can be fractional also.
Input: 1 / | \ 2 3 4 S = 3 Output: 2 All the edges can be assigned weights of 1, so the longest path will in terms of weight will be 2--1--4 or 2--1--3 Input: 1 / 2 / \ 3 4 / \ 5 6 S = 1 Output: 0.50 Assign the given below weights to edges. 1--2: 0.25 2--3: 0.25 2--4: 0 4--5: 0.25 4--6: 0.25 Hence the longest path in terms of weight is 1--2--3 or 1--2--4--5 or 1--2--4--6.
Approach: The property of a tree that a path can have a maximum of two leaf nodes in it can be used to solve the above problem. So if we assign weights only to the edges connecting the leaf nodes, and assign other edges to 0. Then every edge connecting to the leaf nodes will be assigned s/(number of leaf nodes). Since a path can contain a maximum of two leaf nodes, hence the longest path will be 2 * (s/number of leaf nodes).
Below is the implementation of the above approach:
- Root to leaf path sum equal to a given number
- Find the maximum sum leaf to root path in a Binary Tree
- Remove all nodes which don't lie in any path with sum>= k
- Find the maximum path sum between two leaves of a binary tree
- Maximum Path Sum in a Binary Tree
- Maximum Consecutive Increasing Path Length in Binary Tree
- Longest consecutive sequence in Binary tree
- Check if there is a root to leaf path with given sequence
- Find if there is a pair in root to a leaf path with sum equals to root's data
- Longest path in an undirected tree
- Print path from root to a given node in a binary tree
- Print the path common to the two paths from the root to the two given nodes
- Shortest path between two nodes in array like representation of binary tree
- Print common nodes on path from root (or common ancestors)
- Longest word in ternary search 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 : rituraj_jain