Given an N-ary tree T of N nodes, the task is to calculate the longest path between any two nodes(also known as the diameter of the tree).
Different approaches to solve these problems have already been discussed:
In this post, we will be discussing an approach which uses Dynamic Programming on Trees.
There are two possibilities for the diameter to exist:
- Case 1: Suppose the diameter starts from a node and ends at some node in its subtree. Let’s say that there exist a node x such that the longest path starts from node x and goes into its subtree and ends at some node in the subtree itself. Let’s define this path length by dp1[x].
- Case 2: Suppose the diameter or the longest path starts in subtree of a node x, passes through it and ends in it’s subtree. Let’s define this path by dp2[x].
If for all nodes x, we take a maximum of dp1[x], dp2[x], then we will get the diameter of the tree.
For the case-1, to find dp1[node], we need to find the maximum of all dp1[x], where x is the children of node. And dp1[node] will be equal to 1 + max(dp1[children1], dp1[children2], ..).
For the case-2, to find dp2[node], we need to find the two maximum of all dp1[x], where x is the children of node. And dp2[node] will be equal to 1 + max 2 of(dp1[children1], dp1[children2], ..).
We can easily run a DFS and find the maximum of both dp1[node] and dp2[node] for every to get the diameter of the tree.
Below is the implementation of the above approach:
Diameter of the given tree is 4
- Diameter of an N-ary tree
- Diameter of a tree using DFS
- Diameter of n-ary tree using BFS
- Diameter of a Binary Tree
- Diameter of a Binary Tree in O(n) [A new method]
- Possible edges of a tree for given diameter, height and vertices
- Diameter of a Binary Indexed Tree with N nodes
- Make a tree with n vertices , d diameter and at most vertex degree k
- Finding the lexicographically smallest diameter in a binary tree
- Find number of edges that can be broken in a tree such that Bitwise OR of resulting two trees are equal
- Count the Number of Binary Search Trees present in a Binary Tree
- Generic Trees(N-array Trees)
- Total number of possible Binary Search Trees and Binary Trees with n keys
- Maximum sub-tree sum in a Binary Tree such that the sub-tree is also a BST
- Complexity of different operations in Binary tree, Binary Search Tree and AVL 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.
Improved By : rituraj_jain