The diameter of a tree (sometimes called the width) is the number of nodes on the longest path between two end nodes. In this post, we will see how to print the nodes involved in the diameter of the tree. The diagram below shows two trees each with diameter nine, the leaves that form the ends of the longest path are shaded (note that there is more than one path in each tree of length nine, but no path longer than nine nodes).
Input: 1 / \ 2 3 / \ 4 5 Output : 4 2 1 3 or 5 2 1 3 Input: 1 / \ 2 3 / \ \ 4 5 6 Output : 4 2 1 3 6 or 5 2 1 3 6
We have already discussed how to find the diameter of a binary tree.Diameter of a Binary tree
We know that Diameter of a tree can be calculated by only using the height function because the diameter of a tree is nothing but the maximum value of (left_height + right_height + 1) for each node.
Now for the node which has the maximum value of (left_height + right_height + 1), we find the longest root to leaf path on the left side and similarly on the right side. Finally, we print left side path, root and right side path.
Time Complexity is O(N). N is the number of nodes in the tree.
9 8 4 2 5 6
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Print the longest path from root to leaf in a Binary tree
- Print the first shortest root to leaf path in a Binary Tree
- Boundary Root to Leaf Path traversal of a Binary Tree
- Find the maximum sum leaf to root path in a Binary Tree
- Print the nodes of binary tree as they become the leaf node
- Print all leaf nodes of a binary tree from right to left
- Print all leaf nodes of a Binary Tree from left to right
- Given a binary tree, print all root-to-leaf paths
- Print Sum and Product of all Non-Leaf nodes in Binary Tree
- Print leaf nodes in binary tree from left to right using one stack
- Print left and right leaf nodes separately in Binary Tree
- Given a binary tree, print out all of its root-to-leaf paths one per line.
- Print All Leaf Nodes of a Binary Tree from left to right | Set-2 ( Iterative Approach )
- Sum of nodes on the longest path from root to leaf node
- GCD from root to leaf path in an N-ary tree
- Print all leaf nodes of an n-ary tree using DFS
- Sum of all leaf nodes of binary tree
- Construct XOR tree by Given leaf nodes of Perfect Binary Tree
- Closest leaf to a given node in Binary Tree
- Count Non-Leaf nodes 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.