Find height of a special binary tree whose leaf nodes are connected
Given a special binary tree whose leaf nodes are connected to form a circular doubly linked list, find its height.
In the above binary tree, 6, 5 and 3 are leaf nodes and they form a circular doubly linked list. Here, the left pointer of leaf node will act as a previous pointer of circular doubly linked list and its right pointer will act as next pointer of circular doubly linked list.
The idea is to follow similar approach as we do for finding height of a normal binary tree. We recursively calculate height of left and right subtrees of a node and assign height to the node as max of the heights of two children plus 1. But left and right child of a leaf node are null for normal binary trees. But, here leaf node is a circular doubly linked list node. So for a node to be a leaf node, we check if node’s left’s right is pointing to the node and its right’s left is also pointing to the node itself.
Below is the implementation of above idea –
link brightness_4 code
// C++ program to calculate height of a special tree
// whose leaf nodes forms a circular doubly linked list
// A binary tree Node
Node *left, *right;
// function to check if given node is a leaf node or node
// If given node's left's right is pointing to given node
// and its right's left is pointing to the node itself
// then it's a leaf
returnnode->left && node->left->right == node &&
node->right && node->right->left == node;
/* Compute the height of a tree -- the number of
Nodes along the longest path from the root node
down to the farthest leaf node.*/
// if node is NULL, return 0
if(node == NULL)
// if node is a leaf node, return 1
// compute the depth of each subtree and take maximum
Console.WriteLine("Height of tree is "+ maxDepth(root));
// This code is contributed by 29AjayKumar
Height of tree is 4
This article is contributed by Aditya Goel. 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 write comments if you find anything incorrect, or you want to share more information about the topic discussed above.