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).

Examples:
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.
C++
// C++ program to print the longest leaf to leaf// path#include <bits/stdc++.h>using namespace std;// Tree node structure used in the programstruct Node { int data; Node *left, *right;};struct Node* newNode(int data){ struct Node* node = new Node; node->data = data; node->left = node->right = NULL; return (node);}// Function to find height of a treeint height(Node* root, int& ans, Node*(&k;), int& lh, int& rh, int& f){ if (root == NULL) return 0; int left_height = height(root->left, ans, k, lh, rh, f); int right_height = height(root->right, ans, k, lh, rh, f); // update the answer, because diameter of a // tree is nothing but maximum value of // (left_height + right_height + 1) for each node if (ans < 1 + left_height + right_height) { ans = 1 + left_height + right_height; // save the root, this will help us finding the // left and the right part of the diameter k = root; // save the height of left & right subtree as well. lh = left_height; rh = right_height; } return 1 + max(left_height, right_height);}// prints the root to leaf pathvoid printArray(int ints[], int len, int f){ int i; // print left part of the path in reverse order if (f == 0) { for (i = len - 1; i >= 0; i--) { printf("%d ", ints[i]); } } // print right part of the path else if (f == 1) { for (i = 0; i < len; i++) { printf("%d ", ints[i]); } }}// this function finds out all the root to leaf pathsvoid printPathsRecur(Node* node, int path[], int pathLen, int max, int& f){ if (node == NULL) return; // append this node to the path array path[pathLen] = node->data; pathLen++; // If it's a leaf, so print the path that led to here if (node->left == NULL && node->right == NULL) { // print only one path which is equal to the // height of the tree. if (pathLen == max && (f == 0 || f == 1)) { printArray(path, pathLen, f); f = 2; } } else { // otherwise try both subtrees printPathsRecur(node->left, path, pathLen, max, f); printPathsRecur(node->right, path, pathLen, max, f); }}// Computes the diameter of a binary tree with given root.void diameter(Node* root){ if (root == NULL) return; // lh will store height of left subtree // rh will store height of right subtree int ans = INT_MIN, lh = 0, rh = 0; // f is a flag whose value helps in printing // left & right part of the diameter only once int f = 0; Node* k; int height_of_tree = height(root, ans, k, lh, rh, f); int lPath[100], pathlen = 0; // print the left part of the diameter printPathsRecur(k->left, lPath, pathlen, lh, f); printf("%d ", k->data); int rPath[100]; f = 1; // print the right part of the diameter printPathsRecur(k->right, rPath, pathlen, rh, f);}// Driver codeint main(){ // Enter the binary tree ... // 1 // / \ // 2 3 // / \ // 4 5 // \ / \ // 8 6 7 // / // 9 struct Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->left->right->left = newNode(6); root->left->right->right = newNode(7); root->left->left->right = newNode(8); root->left->left->right->left = newNode(9); diameter(root); return 0;} |
Python3
# Python3 program to print the longest# leaf to leaf path# Tree node structure used in the programclass Node: def __init__(self, x): self.data = x self.left = None self.right = None# Function to find height of a treedef height(root): global ans, k, lh, rh, f if (root == None): return 0 left_height = height(root.left) right_height = height(root.right) # Update the answer, because diameter of a # tree is nothing but maximum value of # (left_height + right_height + 1) for each node if (ans < 1 + left_height + right_height): ans = 1 + left_height + right_height # Save the root, this will help us finding the # left and the right part of the diameter k = root # Save the height of left & right # subtree as well. lh = left_height rh = right_height return 1 + max(left_height, right_height)# Prints the root to leaf pathdef printArray(ints, lenn, f): # Print left part of the path # in reverse order if (f == 0): for i in range(lenn - 1, -1, -1): print(ints[i], end = " ") # Print right part of the path elif (f == 1): for i in range(lenn): print(ints[i], end = " ")# This function finds out all the# root to leaf pathsdef printPathsRecur(node, path, maxm, pathlen): global f if (node == None): return # Append this node to the path array path[pathlen] = node.data pathlen += 1 # If it's a leaf, so print the # path that led to here if (node.left == None and node.right == None): # Print only one path which is equal to the # height of the tree. # print(pathlen,"---",maxm) if (pathlen == maxm and (f == 0 or f == 1)): # print("innn") printArray(path, pathlen,f) f = 2 else: # Otherwise try both subtrees printPathsRecur(node.left, path, maxm, pathlen) printPathsRecur(node.right, path, maxm, pathlen)# Computes the diameter of a binary # tree with given root.def diameter(root): global ans, lh, rh, f, k, pathLen if (root == None): return # f is a flag whose value helps in printing # left & right part of the diameter only once height_of_tree = height(root) lPath = [0 for i in range(100)] # print(lh,"--",rh) # Print the left part of the diameter printPathsRecur(k.left, lPath, lh, 0); print(k.data, end = " ") rPath = [0 for i in range(100)] f = 1 # Print the right part of the diameter printPathsRecur(k.right, rPath, rh, 0) # Driver codeif __name__ == '__main__': k, lh, rh, f, ans, pathLen = None, 0, 0, 0, 0 - 10 ** 19, 0 # Enter the binary tree ... # 1 # / \ # 2 3 # / \ # 4 5 # \ / \ # 8 6 7 # / # 9 root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) root.left.right.left = Node(6) root.left.right.right = Node(7) root.left.left.right = Node(8) root.left.left.right.left = Node(9) diameter(root) # This code is contributed by mohit kumar 29 |
9 8 4 2 5 6
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

