Find height of a special binary tree whose leaf nodes are connected - GeeksforGeeks

31 Mar, 2022
Given a special binary tree whose leaf nodes are connected to form a circular doubly linked list, find its height.
For example, 
         1 
       /   \ 
      2      3 
    /  \ 
   4    5
  /   
 6 
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 –  
C++
Java
Python3
C#
Javascript
// C++ program to calculate height of a special tree// whose leaf nodes forms a circular doubly linked list#include <bits/stdc++.h>using namespace std; // A binary tree Nodestruct Node {    int data;    Node *left, *right;}; // function to check if given node is a leaf node or nodebool isLeaf(Node* 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    return node->left && node->left->right == node           && node->right && node->right->left == node;} /* Compute the height of a tree -- the number ofNodes along the longest path from the root nodedown to the farthest leaf node.*/int maxDepth(Node* node){    // if node is NULL, return 0    if (node == NULL)        return 0;     // if node is a leaf node, return 1    if (isLeaf(node))        return 1;     // compute the depth of each subtree and take maximum    return 1           + max(maxDepth(node->left),                 maxDepth(node->right));} // Helper function that allocates a new tree nodeNode* newNode(int data){    Node* node = new Node;    node->data = data;    node->left = NULL;    node->right = NULL;     return node;} // Driver codeint main(){    Node* root = newNode(1);     root->left = newNode(2);    root->right = newNode(3);    root->left->left = newNode(4);    root->left->right = newNode(5);    root->left->left->left = newNode(6);     // Given tree contains 3 leaf nodes    Node* L1 = root->left->left->left;    Node* L2 = root->left->right;    Node* L3 = root->right;     // create circular doubly linked list out of    // leaf nodes of the tree     // set next pointer of linked list    L1->right = L2, L2->right = L3, L3->right = L1;     // set prev pointer of linked list    L3->left = L2, L2->left = L1, L1->left = L3;     // calculate height of the tree    cout << "Height of tree is " << maxDepth(root);     return 0;}
// Java implementation to calculate height of a special tree// whose leaf nodes forms a circular doubly linked listimport java.io.*;import java.util.*; // User defined node classclass Node {    int data;    Node left, right;    // Constructor to create a new tree node    Node(int key)    {        data = key;        left = right = null;    }} class GFG {     // function to check if given node is a leaf node or    // node    static boolean isLeaf(Node 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        return (node.left != null && node.left.right == node                && node.right != null                && 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.*/    static int maxDepth(Node node)    {        // if node is NULL, return 0        if (node == null)            return 0;         // if node is a leaf node, return 1        if (isLeaf(node))            return 1;         // compute the depth of each subtree and take        // maximum        return 1            + Math.max(maxDepth(node.left),                       maxDepth(node.right));    }     // Driver code    public static void main(String args[])    {        Node root = new Node(1);         root.left = new Node(2);        root.right = new Node(3);        root.left.left = new Node(4);        root.left.right = new Node(5);        root.left.left.left = new Node(6);         // Given tree contains 3 leaf nodes        Node L1 = root.left.left.left;        Node L2 = root.left.right;        Node L3 = root.right;         // create circular doubly linked list out of        // leaf nodes of the tree         // set next pointer of linked list        L1.right = L2;        L2.right = L3;        L3.right = L1;         // set prev pointer of linked list        L3.left = L2;        L2.left = L1;        L1.left = L3;         // calculate height of the tree        System.out.println("Height of tree is "                           + maxDepth(root));    }}// This code is contributed by rachana soma
""" program to Delete a Tree """ # Helper function that allocates a new# node with the given data and None# left and right pointers.  class newNode:     # Construct to create a new node    def __init__(self, key):        self.data = key        self.left = None        self.right = None # function to check if given node is a leaf node or node  def isLeaf(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    return node.left and node.left.right == node and \        node.right and node.right.left == node  """ Compute the height of a tree -- the number ofNodes along the longest path from the root nodedown to the farthest leaf node."""  def maxDepth(node):     # if node is None, return 0    if (node == None):        return 0     # if node is a leaf node, return 1    if (isLeaf(node)):        return 1     # compute the depth of each subtree and take maximum    return 1 + max(maxDepth(node.left), maxDepth(node.right))  # Driver Codeif __name__ == '__main__':    root = newNode(1)     root.left = newNode(2)    root.right = newNode(3)    root.left.left = newNode(4)    root.left.right = newNode(5)    root.left.left.left = newNode(6)     # Given tree contains 3 leaf nodes    L1 = root.left.left.left    L2 = root.left.right    L3 = root.right     # create circular doubly linked list out of    # leaf nodes of the tree     # set next pointer of linked list    L1.right = L2    L2.right = L3    L3.right = L1     # set prev pointer of linked list    L3.left = L2    L2.left = L1    L1.left = L3     # calculate height of the tree    print("Height of tree is ", maxDepth(root)) # This code is contributed by# Shubham Singh(SHUBHAMSINGH10)
// C# implementation to calculate height of a special tree// whose leaf nodes forms a circular doubly linked listusing System; // User defined node classpublic class Node {    public int data;    public Node left, right;    // Constructor to create a new tree node    public Node(int key)    {        data = key;        left = right = null;    }} public class GFG {     // function to check if given node is a leaf node or    // node    static bool isLeaf(Node 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        return (node.left != null && node.left.right == node                && node.right != null                && 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.*/    static int maxDepth(Node node)    {        // if node is NULL, return 0        if (node == null)            return 0;         // if node is a leaf node, return 1        if (isLeaf(node))            return 1;         // compute the depth of each subtree and take        // maximum        return 1            + Math.Max(maxDepth(node.left),                       maxDepth(node.right));    }     // Driver code    public static void Main(String[] args)    {        Node root = new Node(1);         root.left = new Node(2);        root.right = new Node(3);        root.left.left = new Node(4);        root.left.right = new Node(5);        root.left.left.left = new Node(6);         // Given tree contains 3 leaf nodes        Node L1 = root.left.left.left;        Node L2 = root.left.right;        Node L3 = root.right;         // create circular doubly linked list out of        // leaf nodes of the tree         // set next pointer of linked list        L1.right = L2;        L2.right = L3;        L3.right = L1;         // set prev pointer of linked list        L3.left = L2;        L2.left = L1;        L1.left = L3;         // calculate height of the tree        Console.WriteLine("Height of tree is "                          + maxDepth(root));    }} // This code is contributed by 29AjayKumar
<script>// Javascript implementation to calculate height of a special tree// whose leaf nodes forms a circular doubly linked listclass Node{    constructor(key)    {        this.data = key;        this.left = this.right = null;    }} // function to check if given node is a leaf node or    // nodefunction isLeaf(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        return (node.left != null && node.left.right == node                && node.right != null                && 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.*/function maxDepth(node){      // if node is NULL, return 0        if (node == null)            return 0;           // if node is a leaf node, return 1        if (isLeaf(node))            return 1;           // compute the depth of each subtree and take        // maximum        return 1            + Math.max(maxDepth(node.left),                       maxDepth(node.right));} // Driver codelet root = new Node(1);   root.left = new Node(2);root.right = new Node(3);root.left.left = new Node(4);root.left.right = new Node(5);root.left.left.left = new Node(6); // Given tree contains 3 leaf nodeslet L1 = root.left.left.left;let L2 = root.left.right;let L3 = root.right; // create circular doubly linked list out of// leaf nodes of the tree // set next pointer of linked listL1.right = L2;L2.right = L3;L3.right = L1; // set prev pointer of linked listL3.left = L2;L2.left = L1;L1.left = L3; // calculate height of the treedocument.write("Height of tree is "                   + maxDepth(root)); // This code is contributed by rag2127</script>
Output: 
Height of tree is 4
YouTubeGeeksforGeeks507K subscribersFind height of a special binary tree whose leaf nodes are connected | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:03•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=bCUSbEYWv-o" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
&list=PLqM7alHXFySHCXD7r1J0ky9Zg_GBB1dbk
This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. 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.
 
rachana soma
SHUBHAMSINGH10
29AjayKumar
pragup
rag2127
saurabh1990aror
simmytarika5
Amazon
Tree
Amazon
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Tree Data Structure
DFS traversal of a tree using recursion
Top 50 Tree Coding Problems for Interviews
Find the node with minimum value in a Binary Search Tree
Print Binary Tree in 2-Dimensions
Real-time application of Data Structures
Threaded Binary Tree
Difference between Min Heap and Max Heap
Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash)
Find maximum (or minimum) in Binary Tree