Last active
July 3, 2019 09:10
-
-
Save manojnaidu619/0eabdd2072aa6e24d7ffc283009f57ec to your computer and use it in GitHub Desktop.
Getting height & leaf nodes of Left and Right subtree in a BST
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
using namespace std; | |
struct Node{ | |
struct Node *lchild; | |
int data; | |
int height; | |
struct Node *rchild; | |
}*root=NULL,*lleaf=NULL,*rleaf=NULL; // Pointing to Left and Right leaf nodes in BST | |
void insert(int key){ | |
struct Node *p = root,*q=NULL,*temp; | |
if(root==NULL){ | |
temp = new Node; | |
temp->lchild = NULL; | |
temp->data = key; | |
temp->height = 1; // By default the height of root node is taken as 1 | |
temp->rchild = NULL; | |
root = temp; | |
rleaf=lleaf=root; | |
}else{ | |
while(p!=NULL){ | |
q=p; | |
if(key < p->data){ | |
p=p->lchild; | |
} | |
else if(key > p->data){ | |
p=p->rchild; | |
} | |
else{ | |
return; | |
} | |
} | |
temp = new Node; | |
temp -> data = key; | |
temp -> height = q->height+1; // incrementing the height by 1 for every node insertion | |
temp -> rchild=NULL; | |
temp->lchild = NULL; | |
if(key > q->data){ | |
q->rchild = temp; | |
key < root->data ? lleaf = temp : rleaf = temp; // Logic line | |
}else{ | |
q->lchild = temp; | |
key > root->data ? rleaf = temp : lleaf = temp; // Logic line | |
} | |
} | |
} | |
int main(){ | |
insert(30); | |
insert(20); | |
insert(40); | |
insert(10); | |
insert(25); | |
cout << lleaf->data << " " << lleaf->height << endl; | |
cout << rleaf->data << " " << rleaf->height << endl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment