You are on page 1of 33

1. 1.

Iterative program to count leaf nodes in a Binary Tree (level order traversal)(uses queue)

2. Program to count leaf nodes in a binary tree(recursion)

3. Find size of binary tree(recursion)

4. Binary search tree (vig)

5. C++ Program to Implement Binary Search Tree


6. Search and insertion in bst

7. Check if each internal node of a BST has exactly one child(pre-order traversal)

8. Largest number in BST which is less than or equal to N

9. Find the node with minimum value in a Binary Search Tree

10. Remove BST keys outside the given range

11. C Program to Construct a Binary Search Tree and perform deletion and inorder traversal

12. Write a program to Delete a Tree.

13. Write a program to Delete a Tree.(del leaf node, node with one child,node with 2 children)

14. Remove all leaf nodes.

15. Print all nodes that don’t have sibling

16. Print Ancestors of a given node in Binary Tree

1.

/* Function to get the count of leaf Nodes in

a binary tree*/

unsigned int getLeafCount(struct Node* node)

// If tree is empty

if (!node)
return 0;

// Initialize empty queue.

queue<Node *> q;

// Do level order traversal starting from root

int count = 0; // Initialize count of leaves

q.push(node);

while (!q.empty())

struct Node *temp = q.front();

q.pop();

if (temp->left != NULL)

q.push(temp->left);

if (temp->right != NULL)

q.push(temp->right);

if (temp->left == NULL && temp->right == NULL)

count++;

return count;

2.

unsigned int getLeafCount(struct node* node)

{
if(node==NULL)

return 0;

if(node->left==NULL && node->right==NULL)

return 1;

else

return getLeafCount(node->left)+getLeafCount(node->right);

3.

/* Computes the number of nodes in a tree. */

int size(struct node* node)

if (node==NULL)

return 0;

else

return(size(node->left) + 1 + size(node->right));

4.

#include<iostream>

using namespace std;

struct node

int data;

char name[50];

node* right;

node* left;
};

void traversal(node* root)

if(root!=NULL)

traversal(root->left);

cout<<endl<<root->data<<endl<<root->name;

traversal(root->right);

node* create(int info)

node* temp=new node;

temp->data=info;

cout<<"enter the employee name:";

cin>>temp->name;

temp->right=temp->left=NULL;

return temp;

node* insert(node* temp,int info)

if (temp==NULL)

return create(info);
if(info<temp->data)

temp->left=insert(temp->left,info);

else if( info>temp->data)

temp->right=insert(temp->right,info);

return temp;

int main()

node* root=NULL;

int opt;

while(1)

cout<<"1.insert"<<endl<<"2.traverse"<<endl<<"3.exit";

cin>>opt;

switch(opt)

case 1:

int inf;

cout<<"enter the id";

cin>>inf;

root=insert(root,inf);

break;

case 2:

traversal(root);
break;

case 3:

exit(0);

return 0;

5.

# include <iostream>
# include <cstdlib>
using namespace std;
/*
* Node Declaration
*/
struct node
{
int info;
struct node *left;
struct node *right;
}*root;

/*
* Class Declaration
*/
class BST
{
public:
void find(int, node **, node **);
void insert(int);
void del(int);
void case_a(node *,node *);
void case_b(node *,node *);
void case_c(node *,node *);
void preorder(node *);
void inorder(node *);
void postorder(node *);
void display(node *, int);
BST()
{
root = NULL;
}
};
/*
* Main Contains Menu
*/
int main()
{
int choice, num;
BST bst;
node *temp;
while (1)
{
cout<<"-----------------"<<endl;
cout<<"Operations on BST"<<endl;
cout<<"-----------------"<<endl;
cout<<"1.Insert Element "<<endl;
cout<<"2.Delete Element "<<endl;
cout<<"3.Inorder Traversal"<<endl;
cout<<"4.Preorder Traversal"<<endl;
cout<<"5.Postorder Traversal"<<endl;
cout<<"6.Display"<<endl;
cout<<"7.Quit"<<endl;
cout<<"Enter your choice : ";
cin>>choice;
switch(choice)
{
case 1:
temp = new node;
cout<<"Enter the number to be inserted : ";
cin>>temp->info;
bst.insert(root, temp);
case 2:
if (root == NULL)
{
cout<<"Tree is empty, nothing to delete"<<endl;
continue;
}
cout<<"Enter the number to be deleted : ";
cin>>num;
bst.del(num);
break;
case 3:
cout<<"Inorder Traversal of BST:"<<endl;
bst.inorder(root);
cout<<endl;
break;
case 4:
cout<<"Preorder Traversal of BST:"<<endl;
bst.preorder(root);
cout<<endl;
break;
case 5:
cout<<"Postorder Traversal of BST:"<<endl;
bst.postorder(root);
cout<<endl;
break;
case 6:
cout<<"Display BST:"<<endl;
bst.display(root,1);
cout<<endl;
break;
case 7:
exit(1);
default:
cout<<"Wrong choice"<<endl;
}
}
}
/*
* Find Element in the Tree
*/
void BST::find(int item, node **par, node **loc)
{
node *ptr, *ptrsave;
if (root == NULL)
{
*loc = NULL;
*par = NULL;
return;
}
if (item == root->info)
{
*loc = root;
*par = NULL;
return;
}
if (item < root->info)
ptr = root->left;
else
ptr = root->right;
ptrsave = root;
while (ptr != NULL)
{
if (item == ptr->info)
{
*loc = ptr;
*par = ptrsave;
return;
}
ptrsave = ptr;
if (item < ptr->info)
ptr = ptr->left;
else
ptr = ptr->right;
}
*loc = NULL;
*par = ptrsave;
}

/*
* Inserting Element into the Tree
*/
void BST::insert(node *tree, node *newnode)
{
if (root == NULL)
{
root = new node;
root->info = newnode->info;
root->left = NULL;
root->right = NULL;
cout<<"Root Node is Added"<<endl;
return;
}
if (tree->info == newnode->info)
{
cout<<"Element already in the tree"<<endl;
return;
}
if (tree->info > newnode->info)
{
if (tree->left != NULL)
{
insert(tree->left, newnode);
}
else
{
tree->left = newnode;
(tree->left)->left = NULL;
(tree->left)->right = NULL;
cout<<"Node Added To Left"<<endl;
return;
}
}
else
{
if (tree->right != NULL)
{
insert(tree->right, newnode);
}
else
{
tree->right = newnode;
(tree->right)->left = NULL;
(tree->right)->right = NULL;
cout<<"Node Added To Right"<<endl;
return;
}
}
/*
* Delete Element from the tree
*/
void BST::del(int item)
{
node *parent, *location;
if (root == NULL)
{
cout<<"Tree empty"<<endl;
return;
}
find(item, &parent, &location);
if (location == NULL)
{
cout<<"Item not present in tree"<<endl;
return;
}
if (location->left == NULL && location->right == NULL)
case_a(parent, location);
if (location->left != NULL && location->right == NULL)
case_b(parent, location);
if (location->left == NULL && location->right != NULL)
case_b(parent, location);
if (location->left != NULL && location->right != NULL)
case_c(parent, location);
free(location);
}

/*
* Case A
*/
void BST::case_a(node *par, node *loc )
{
if (par == NULL)
{
root = NULL;
}
else
{
if (loc == par->left)
par->left = NULL;
else
par->right = NULL;
}
}

/*
* Case B
*/
void BST::case_b(node *par, node *loc)
{
node *child;
if (loc->left != NULL)
child = loc->left;
else
child = loc->right;
if (par == NULL)
{
root = child;
}
else
{
if (loc == par->left)
par->left = child;
else
par->right = child;
}
}

/*
* Case C
*/
void BST::case_c(node *par, node *loc)
{
node *ptr, *ptrsave, *suc, *parsuc;
ptrsave = loc;
ptr = loc->right;
while (ptr->left != NULL)
{
ptrsave = ptr;
ptr = ptr->left;
}
suc = ptr;
parsuc = ptrsave;
if (suc->left == NULL && suc->right == NULL)
case_a(parsuc, suc);
else
case_b(parsuc, suc);
if (par == NULL)
{
root = suc;
}
else
{
if (loc == par->left)
par->left = suc;
else
par->right = suc;
}
suc->left = loc->left;
suc->right = loc->right;
}

/*
* Pre Order Traversal
*/
void BST::preorder(node *ptr)
{
if (root == NULL)
{
cout<<"Tree is empty"<<endl;
return;
}
if (ptr != NULL)
{
cout<<ptr->info<<" ";
preorder(ptr->left);
preorder(ptr->right);
}
}
/*
* In Order Traversal
*/
void BST::inorder(node *ptr)
{
if (root == NULL)
{
cout<<"Tree is empty"<<endl;
return;
}
if (ptr != NULL)
{
inorder(ptr->left);
cout<<ptr->info<<" ";
inorder(ptr->right);
}
}

/*
* Postorder Traversal
*/
void BST::postorder(node *ptr)
{
if (root == NULL)
{
cout<<"Tree is empty"<<endl;
return;
}
if (ptr != NULL)
{
postorder(ptr->left);
postorder(ptr->right);
cout<<ptr->info<<" ";
}
}

/*
* Display Tree Structure
*/
void BST::display(node *ptr, int level)
{
int i;
if (ptr != NULL)
{
{
display(ptr->right, level+1);
cout<<endl;
if (ptr == root)
cout<<"Root->: ";
else
{
for (i = 0;i < level;i++)
cout<<" ";
}
cout<<ptr->info;
display(ptr->left, level+1);
}
}

6.
// A utility function to do inorder traversal of BST

void inorder(struct node *root)

if (root != NULL)
{

inorder(root->left);

printf("%d \n", root->key);

inorder(root->right);

/* A utility function to insert a new node with given key in BST */

struct node* insert(struct node* node, int key)

/* If the tree is empty, return a new node */

if (node == NULL) return newNode(key);

/* Otherwise, recur down the tree */

if (key < node->key)

node->left = insert(node->left, key);

else if (key > node->key)

node->right = insert(node->right, key);

/* return the (unchanged) node pointer */

return node;

7.

bool hasOnlyOneChild(int pre[], int size)

int nextDiff, lastDiff;


for (int i=0; i<size-1; i++)

nextDiff = pre[i] - pre[i+1];

lastDiff = pre[i] - pre[size-1];

if (nextDiff*lastDiff < 0)

return false;;

return true;

// driver program to test above function

int main()

int pre[] = {8, 3, 5, 7, 6};

int size = sizeof(pre)/sizeof(pre[0]);

if (hasOnlyOneChild(pre, size) == true )

printf("Yes");

else

printf("No");

return 0;

8.

// To insert a new node in BST

Node* insert(Node* node, int key)


{

// if tree is empty return new node

if (node == NULL)

return newNode(key);

// if key is less then or grater then

// node value then recur down the tree

if (key < node->key)

node->left = insert(node->left, key);

else if (key > node->key)

node->right = insert(node->right, key);

// return the (unchanged) node pointer

return node;

// function to find max value less then N

int findMaxforN(Node* root, int N)

/* If leaf node reached and is greater than N*/

if (root->left == NULL && root->right == NULL &&

root->key > N)

return -1;

/* If node's value is less than N and right value


is NULL or grater than then return the node

value*/

if ((root->key <= N && root->right == NULL) ||

(root->key <= N && root->right->key > N))

return root->key;

// if node value is grater than N search in the

// left subtree

if (root->key >= N)

return findMaxforN(root->left, N);

// if node value is less than N search in the

// right subtree

else

return findMaxforN(root->right, N);

9.

/* Give a binary search tree and a number,

inserts a new node with the given number in

the correct place in the tree. Returns the new

root pointer which the caller should then use

(the standard trick to avoid using reference

parameters). */

struct node* insert(struct node* node, int data)

{
/* 1. If the tree is empty, return a new,

single node */

if (node == NULL)

return(newNode(data));

else

/* 2. Otherwise, recur down the tree */

if (data <= node->data)

node->left = insert(node->left, data);

else

node->right = insert(node->right, data);

/* return the (unchanged) node pointer */

return node;

/* Given a non-empty binary search tree,

return the minimum data value found in that

tree. Note that the entire tree does not need

to be searched. */

int minValue(struct node* node) {

struct node* current = node;

/* loop down to find the leftmost leaf */


while (current->left != NULL) {

current = current->left;

return(current->data);

10.

// Removes all nodes having value outside the given range and returns the root

// of modified tree

node* removeOutsideRange(node *root, int min, int max)

// Base Case

if (root == NULL)

return NULL;

// First fix the left and right subtrees of root

root->left = removeOutsideRange(root->left, min, max);

root->right = removeOutsideRange(root->right, min, max);

// Now fix the root. There are 2 possible cases for toot

// 1.a) Root's key is smaller than min value (root is not in range)

if (root->key < min)

node *rChild = root->right;

delete root;

return rChild;
}

// 1.b) Root's key is greater than max value (root is not in range)

if (root->key > max)

node *lChild = root->left;

delete root;

return lChild;

// 2. Root is in range

return root;

// A utility function to create a new BST node with key as given num

node* newNode(int num)

node* temp = new node;

temp->key = num;

temp->left = temp->right = NULL;

return temp;

// A utility function to insert a given key to BST

node* insert(node* root, int key)

if (root == NULL)
return newNode(key);

if (root->key > key)

root->left = insert(root->left, key);

else

root->right = insert(root->right, key);

return root;

// Utility function to traverse the binary tree after conversion

void inorderTraversal(node* root)

if (root)

inorderTraversal( root->left );

cout << root->key << " ";

inorderTraversal( root->right );

11.

/* A utility function to insert a node at the beginning of

a linked list*/

void push(struct Node** head_ref, int new_data);

/* A utility function to check if given data is present in a list */

bool isPresent(struct Node *head, int data);


/* Function to get union of two linked lists head1 and head2 */

struct Node *getUnion(struct Node *head1, struct Node *head2)

struct Node *result = NULL;

struct Node *t1 = head1, *t2 = head2;

// Insert all elements of list1 to the result list

while (t1 != NULL)

push(&result, t1->data);

t1 = t1->next;

// Insert those elements of list2 which are not

// present in result list

while (t2 != NULL)

if (!isPresent(result, t2->data))

push(&result, t2->data);

t2 = t2->next;

return result;

}
/* Function to get intersection of two linked lists

head1 and head2 */

struct Node *getIntersection(struct Node *head1,

struct Node *head2)

struct Node *result = NULL;

struct Node *t1 = head1;

// Traverse list1 and search each element of it in

// list2. If the element is present in list 2, then

// insert the element to result

while (t1 != NULL)

if (isPresent(head2, t1->data))

push (&result, t1->data);

t1 = t1->next;

return result;

/* A utility function to insert a node at the begining of a linked list*/

void push (struct Node** head_ref, int new_data)

{
/* allocate node */

struct Node* new_node =

(struct Node*) malloc(sizeof(struct Node));

/* put in the data */

new_node->data = new_data;

/* link the old list off the new node */

new_node->next = (*head_ref);

/* move the head to point to the new node */

(*head_ref) = new_node;

/* A utility function to print a linked list*/

void printList (struct Node *node)

while (node != NULL)

printf ("%d ", node->data);

node = node->next;

/* A utility function that returns true if data is


present in linked list else return false */

bool isPresent (struct Node *head, int data)

struct Node *t = head;

while (t != NULL)

if (t->data == data)

return 1;

t = t->next;

return 0;

12.

/* This function traverses tree in post order to

to delete each and every node of the tree */

void deleteTree(struct node* node)

if (node == NULL) return;

/* first delete both subtrees */

deleteTree(node->left);

deleteTree(node->right);

/* then delete the node */

printf("\n Deleting node: %d", node->data);


free(node);

13.

// A utility function to create a new BST node

struct node *newNode(int item)

struct node *temp = (struct node *)malloc(sizeof(struct node));

temp->key = item;

temp->left = temp->right = NULL;

return temp;

// A utility function to do inorder traversal of BST

void inorder(struct node *root)

if (root != NULL)

inorder(root->left);

printf("%d ", root->key);

inorder(root->right);

/* A utility function to insert a new node with given key in BST */

struct node* insert(struct node* node, int key)


{

/* If the tree is empty, return a new node */

if (node == NULL) return newNode(key);

/* Otherwise, recur down the tree */

if (key < node->key)

node->left = insert(node->left, key);

else

node->right = insert(node->right, key);

/* return the (unchanged) node pointer */

return node;

/* Given a non-empty binary search tree, return the node with minimum

key value found in that tree. Note that the entire tree does not

need to be searched. */

struct node * minValueNode(struct node* node)

struct node* current = node;

/* loop down to find the leftmost leaf */

while (current->left != NULL)

current = current->left;
return current;

/* Given a binary search tree and a key, this function deletes the key

and returns the new root */

struct node* deleteNode(struct node* root, int key)

// base case

if (root == NULL) return root;

// If the key to be deleted is smaller than the root's key,

// then it lies in left subtree

if (key < root->key)

root->left = deleteNode(root->left, key);

// If the key to be deleted is greater than the root's key,

// then it lies in right subtree

else if (key > root->key)

root->right = deleteNode(root->right, key);

// if key is same as root's key, then This is the node

// to be deleted

else

// node with only one child or no child


if (root->left == NULL)

struct node *temp = root->right;

free(root);

return temp;

else if (root->right == NULL)

struct node *temp = root->left;

free(root);

return temp;

// node with two children: Get the inorder successor (smallest

// in the right subtree)

struct node* temp = minValueNode(root->right);

// Copy the inorder successor's content to this node

root->key = temp->key;

// Delete the inorder successor

root->right = deleteNode(root->right, temp->key);

return root;

}
14.

// Insert a Node in binary search tree.

struct Node* insert(struct Node* root, int data)

if (root == NULL)

return newNode(data);

if (data < root->data)

root->left = insert(root->left, data);

else if (data > root->data)

root->right = insert(root->right, data);

return root;

// Function for inorder traversal in a BST.

void inorder(struct Node* root)

if (root != NULL) {

inorder(root->left);

cout << root->data << " ";

inorder(root->right);

// Delete leaf nodes from binary search tree.

struct Node* leafDelete(struct Node* root)


{

if (root->left == NULL && root->right == NULL) {

free(root);

return NULL;

// Else recursively delete in left and right

// subtrees.

root->left = leafDelete(root->left);

root->right = leafDelete(root->right);

return root;

15.

// Function to print all non-root nodes that don't have a sibling

void printSingles(struct node *root)

// Base case

if (root == NULL)

return;

// If this is an internal node, recur for left

// and right subtrees

if (root->left != NULL && root->right != NULL)

{
printSingles(root->left);

printSingles(root->right);

// If left child is NULL and right is not, print right child

// and recur for right child

else if (root->right != NULL)

cout << root->right->key << " ";

printSingles(root->right);

// If right child is NULL and left is not, print left child

// and recur for left child

else if (root->left != NULL)

cout << root->left->key << " ";

printSingles(root->left);

16.

// Function to insert given key into the tree


void insert(Node*& root, string level, int key)
{
// tree is empty
if (level.length() == 0)
{
root = newNode(key);
return;
}
int i = 0;
Node* ptr = root;
while (i < level.length() - 1)
{
if (level[i++] == 'L')
ptr = ptr->left;
else
ptr = ptr->right;
}

if (level[i] == 'L')
ptr->left = newNode(key);
else
ptr->right = newNode(key);
}

// Recursive function to print all ancestors of given node in a


binary tree. The
// function returns true if node is found in subtree rooted at
given root node
bool printAncestors(Node *root, int node)
{
// base case
if (root == nullptr)
return false;

// return true if given node is found


if (root->data == node)
return true;

// search node in left subtree


bool left = printAncestors(root->left, node);

// search node in right subtree


bool right = false;
if (!left)
right = printAncestors(root->right, node);

// if given node is found in either left or right subtree,


// current node is an ancestor of given node
if (left || right)
cout << root->data << " ";

// return true if node is found


return left || right;
}

You might also like