Find height of a special binary tree whose leaf nodes are connected in C++


Suppose we have a special binary tree, whose leaf nodes are connected to form a circular doubly linked list. We have to find its height. So the left pointer of the left most leaf will act as previous pointer of circular doubly linked list, and its right pointer will act as next pointer of the linked list.

In this case the height finding strategy is similar to the normal binary search tree. We recursively calculate the height of the left and right subtrees of a node and assign height to the node is max of the two children + 1. But here leaves are elements of circular doubly linked list. So for a node to be leaf node we check if the nodes left’s right is pointing to the node and its right’s left is pointing to the node itself.

Example

 Live Demo

#include<iostream>
using namespace std;
class Node {
   public:
      int data;
      Node *left, *right;
};
bool isLeafNode(Node* node) {
   return node->left && node->left->right == node && node->right && node->right->left == node;
}
int findHeight(Node* node) {
   if (node == NULL)
      return 0;
   if (isLeafNode(node))
      return 1;
   return 1 + max(findHeight(node->left), findHeight(node->right));
}
Node* getNode(int data) {
   Node* node = new Node;
   node->data = data;
   node->left = NULL;
   node->right = NULL;
   return node;
}
int main() {
   Node* root = getNode(1);
   root->left = getNode(2);
   root->right = getNode(3);
   root->left->left = getNode(4);
   root->left->right = getNode(5);
   root->left->left->left = getNode(6);
   Node *L1 = root->left->left->left;
   Node *L2 = root->left->right;
   Node *L3 = root->right;
   L1->right = L2, L2->right = L3, L3->right = L1;
   L3->left = L2, L2->left = L1, L1->left = L3;
   cout << "Height of tree is: " << findHeight(root);
}

Output

Height of tree is: 4

Updated on: 17-Dec-2019

127 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements