Why is my create function of binary search tree not working? - data-structures

The create function is supposed to ask the user how many nodes they want to enter and then insert that many elements one by one.
I am using the pre order traversal function to check the creation of the binary search tree
The code runs fine for the input part, where it is asking the user for data to enter, but when it is supposed to show the tree in pre order traversal manner, it does not do anything and exits.
#include <stdio.h>
#include <stdlib.h>
struct Node
{
int data;
struct Node* left;
struct Node* right;
};
void insert(struct Node* root, int x)
{
if(root -> left == NULL && x < root -> data)
{
struct Node* new_node = (struct Node* )malloc(sizeof(struct Node));
new_node -> data = x;
new_node -> left = NULL;
new_node -> right = NULL;
root -> left = new_node;
}
else if(root -> right == NULL && x > root -> data)
{
struct Node* new_node = (struct Node* )malloc(sizeof(struct Node));
new_node -> data = x;
new_node -> left = NULL;
new_node -> right = NULL;
root -> right = new_node;
}
else
{
if(x < root -> data)
{
insert(root -> left, x);
}
else if(x > root -> data)
{
insert(root -> right, x);
}
}
}
void create(struct Node* root)
{
root = (struct Node*)malloc(sizeof(struct Node));
printf("\nHow many nodes do you want to create: ");
int tree_size;
scanf("%d", &tree_size);
printf("\nEnter data for root node: ");
int ent_data;
scanf("%d", &ent_data);
root -> data = ent_data;
root -> left = NULL;
root -> right = NULL;
for(int i=1; i<tree_size; i++)
{
printf("\nEnter data for node: ");
scanf("%d", &ent_data);
insert(root, ent_data);
}
}
void preOrderTraversal(struct Node *root)
{
if(root != NULL)
{
printf("%d, ", root -> data);
preOrderTraversal(root -> left);
preOrderTraversal(root -> right);
}
}
int main()
{
struct Node* root = NULL;
create(root);
preOrderTraversal(root);
return 0;
}

The problem is that create is not going to modify your main's variable root. C arguments are passed by value, so you should do one of the following:
Pass the address of root to the create function, or
Don't pass root as argument at all, but let create return the root pointer.
The second option is to be preferred, because root does not serve as input value for create, but as output.
Not related to your issue, but try to avoid code repetition. There are three places in your code where you call malloc and initialise a node. instead create a function for that and call it at those three places.
Here is the adapted code:
#include <stdio.h>
#include <stdlib.h>
struct Node
{
int data;
struct Node* left;
struct Node* right;
};
// Function to call whenever you need a node instance
struct Node * create_node(int x)
{
struct Node* new_node = (struct Node*) malloc(sizeof(struct Node));
new_node -> data = x;
new_node -> left = NULL;
new_node -> right = NULL;
return new_node;
}
void insert(struct Node* root, int x)
{
if(root -> left == NULL && x < root -> data)
{
root -> left = create_node(x); // Use function
}
else if(root -> right == NULL && x > root -> data)
{
root -> right = create_node(x); // Use function
}
else
{
if(x < root -> data)
{
insert(root -> left, x);
}
else if(x > root -> data)
{
insert(root -> right, x);
}
}
}
struct Node* create() // No parameter, but return type
{
printf("\nHow many nodes do you want to create: ");
int tree_size;
scanf("%d", &tree_size);
printf("\nEnter data for root node: ");
int ent_data;
scanf("%d", &ent_data);
struct Node* root = create_node(ent_data); // Use function
for(int i=1; i<tree_size; i++)
{
printf("\nEnter data for node: ");
scanf("%d", &ent_data);
insert(root, ent_data);
}
return root; // Return the root
}
void preOrderTraversal(struct Node *root)
{
if(root != NULL)
{
printf("%d, ", root -> data);
preOrderTraversal(root -> left);
preOrderTraversal(root -> right);
}
}
int main()
{
struct Node* root = create(); // No argument, but return value
preOrderTraversal(root);
return 0;
}

Related

How to add a node in Binary search tree?

struct node {
int data{};
node *right{nullptr};
node *left{nullptr};
};
class BTree {
private:
node *root;
void insert(node *sr, int num);
public:
BTree();
void buildTree(int num);
};
void BTree::insert(node *sr, int num) {
if (sr == nullptr) {
sr = new node;
sr->data = num;
} else {
if (num < sr->data)
insert(sr->left, num);
else
insert(sr->right, num);
}
}
int main() {
BTree tree;
tree.buildTree(3);
return 0;
}
I am using the above insert method to add a node to Binary Search Tree. But this method is unable to add the node , if i add a number as its root or first node the root remains nullptr.
How do i resolve this issue.
At the first root is nullptr , and I am sending root i.e the nullptr as the argument. As nullptr does refer to any node therefor the root is not getting updated by the operation in the method.
possible solution:
use pointer to pointer, so that address of the node can be passed and and changed.
directly acces the root to do changes.
PROTOTYPE
void insert(node **sr, int num);
BUILD TREE METHOD
void BTree::buildTree(int num) {
insert(&root, num);
}
INSERT METHOD
void BTree::insert(node **sr, int num) {
if (*sr == nullptr) {
*sr = new node;
(*sr)->data = num;
} else {
if (num < (*sr)->data)
insert(&((*sr)->left), num);
else
insert(&((*sr)->right), num);
}
}

Binary Search Tree Traversals

I have just started learning Binary Trees and went ahead and tried to implement my own in C. I am kinda lost as to why only InOrder Traversal is displaying correctly while the other two are wrong. I really can't figure this out. I even directly tried inserting nodes, and the result is the same.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
struct Node
{
int val;
struct Node *left;
struct Node *right;
};
//Allocate Memory for New Node
struct Node* getNewNode(int val)
{
struct Node * ptr = (struct Node*)malloc(sizeof(struct Node));
ptr->val = val;
ptr->left = NULL;
ptr->right = NULL;
return ptr;
}
//Insert Node in Binary Search Tree
struct Node* insertNode(struct Node* root,int val)
{
if(root == NULL)
{
root = getNewNode(val);
}
else if(val <= root->val)
{
root->left = insertNode(root->left,val);
}
else
{
root->right = insertNode(root->right,val);
}
return root;
}
void printInorder(struct Node* root)
{
if(root == NULL) return;
printInorder(root->left);
printf("%d ",root->val);
printInorder(root->right);
}
void printPostOrder(struct Node* root)
{
if(root == NULL) return;
printInorder(root->left);
printInorder(root->right);
printf("%d ",root->val);
}
void printPreOrder(struct Node*root)
{
if(root == NULL) return;
printf("%d ",root->val);
printInorder(root->left);
printInorder(root->right);
}
bool search(struct Node* root,int val)
{
if(root == NULL)
{
return false;
}
else if(val == root->val)
{
return true;
}
else if(val < root->val)
{
return search(root->left,val);
}
else
{
return search(root->right,val);
}
}
int main(void)
{
struct Node * root = NULL; //Tree is Empty
root = insertNode(root,15);
root = insertNode(root,10);
root = insertNode(root,8);
root = insertNode(root,12);
root = insertNode(root,20);
root = insertNode(root,17);
root = insertNode(root,25);
printf("Printing In-Order: \n");
printInorder(root);
printf("\nPrinting Post-Order: \n");
printPostOrder(root);
printf("\nPrinting Pre-Order: \n");
printPreOrder(root);
// if(search(root,11))
// {
// printf("\nValue Found\n");
// }
// else
// {
// printf("\nValue Not Found\n");
// }
return 0;
}
Please help me understand if I am doing this wrong or my understanding of traversals is faulty.
The output is as follows:
output terminal
You have copy-paste errors in printPostOrder and printPreOrder - they both call printInorder where they should be calling themselves.

Lowest Common Ancestor of a Binary Search Tree code doesn't pass

can anyone help me with this code? I cannot figure out where I'm blocked.
Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
TreeNode* res=NULL;
int i=0;
postTrav(root,p,q,res,i);
return res;
}
void postTrav(TreeNode* root, TreeNode* p, TreeNode* q,TreeNode* res,int& i){
if(!root){
return;
}
postTrav(root->left,p,q,res,i);
postTrav(root->right,p,q,res,i);
if(root==p||root==q){
i++;
}
if(i==2){
res=root;
i++;
}
}
You may have a logic bug in addition to this, but, because C [I assume] is call-by-value, setting res and i are changed local to a given function invocation, but then discarded. You'll need to pass around some addresses, as below. Especially, note that res is now TreeNode ** in postTrav.
TreeNode *
lowestCommonAncestor(TreeNode *root, TreeNode *p, TreeNode *q)
{
TreeNode *res = NULL;
int i = 0;
postTrav(root, p, q, &res, &i);
return res;
}
void
postTrav(TreeNode *root, TreeNode *p, TreeNode *q, TreeNode **res, int *i)
{
if (!root) {
return;
}
postTrav(root->left, p, q, res, i);
postTrav(root->right, p, q, res, i);
if (root == p || root == q) {
*i++;
}
if (*i == 2) {
*res = root;
*i++;
}
}
UPDATE:
The above code is fine. But, whenever, I have a function that needs to return or maintain two or more values [in parallel], a technique I use is to create an additional "traversal" or "helper" struct that simplifies the argument passing.
If you needed an additional variable that needed to be modified/maintained across the calls, instead of adding an additional argument to all functions, it becomes easy/easier to just add another variable to the struct. This works particularly well when you're building up your logic as you go along.
Here's the code for the refinement. Notice that fewer arguments need to be pushed/popped. And, this probably executes as fast or faster than the original. Also, for me, trav->res seems a bit cleaner than *res
// traversal "helper" struct
struct _traverse {
TreeNode *p; // not modified
TreeNode *q; // not modified
TreeNode *res; // result
int i; // depth
// add more variables here as desired ...
#ifdef WANT_TRAVERSAL_STATISTICS
int visited_count; // number of nodes we visited
#endif
};
typedef struct _traverse Traverse;
TreeNode *
lowestCommonAncestor(TreeNode *root, TreeNode *p, TreeNode *q)
{
Traverse trav;
trav.p = p;
trav.q = q;
trav.res = NULL;
trav.i = 0;
#ifdef WANT_TRAVERSAL_STATISTICS
trav.visited_count = 0;
#endif
postTrav(root, &trav);
#ifdef WANT_TRAVERSAL_STATISTICS
printf("Visited %d Nodes\n",trav.visited_count);
#endif
return trav.res;
}
void
postTrav(TreeNode *root, Traverse *trav)
{
if (!root) {
return;
}
#ifdef WANT_TRAVERSAL_STATISTICS
trav->visited_count += 1;
#endif
postTrav(root->left, trav);
postTrav(root->right, trav);
if (root == trav->p || root == trav->q) {
trav->i++;
}
if (trav->i == 2) {
trav->res = root;
trav->i++;
}
}
You are not using the property of BST. postTrav should be like this:
TreeNode* postTrav(TreeNode* root, TreeNode* p, TreeNode* q,)
{
if (root == NULL||p==NULL||q==NULL) return NULL;
int n1=p->data;
int n2=q->data;
while (root != NULL)
{
// If both n1 and n2 are smaller than root, then LCA lies in left
if (root->data > n1 && root->data > n2)
root = root->left;
// If both n1 and n2 are greater than root, then LCA lies in right
else if (root->data < n1 && root->data < n2)
root = root->right;
else break;
}
return root;
}

AVL Tree. Print element by position (when sorted)

#include<stdio.h>
#include<stdlib.h>
// An AVL tree node
struct node
{
int key;
struct node *left;
struct node *right;
int height;
};
// A utility function to get maximum of two integers
int max(int a, int b);
// A utility function to get height of the tree
int height(struct node *N)
{
if (N == NULL)
return 0;
return N->height;
}
// A utility function to get maximum of two integers
int max(int a, int b)
{
return (a > b)? a : b;
}
/* Helper function that allocates a new node with the given key and
NULL left and right pointers. */
struct node* newNode(int key)
{
struct node* node = (struct node*)
malloc(sizeof(struct node));
node->key = key;
node->left = NULL;
node->right = NULL;
node->height = 1; // new node is initially added at leaf
return(node);
}
// A utility function to right rotate subtree rooted with y
// See the diagram given above.
struct node *rightRotate(struct node *y)
{
struct node *x = y->left;
struct node *T2 = x->right;
// Perform rotation
x->right = y;
y->left = T2;
// Update heights
y->height = max(height(y->left), height(y->right))+1;
x->height = max(height(x->left), height(x->right))+1;
// Return new root
return x;
}
// A utility function to left rotate subtree rooted with x
// See the diagram given above.
struct node *leftRotate(struct node *x)
{
struct node *y = x->right;
struct node *T2 = y->left;
// Perform rotation
y->left = x;
x->right = T2;
// Update heights
x->height = max(height(x->left), height(x->right))+1;
y->height = max(height(y->left), height(y->right))+1;
// Return new root
return y;
}
// Get Balance factor of node N
int getBalance(struct node *N)
{
if (N == NULL)
return 0;
return height(N->left) - height(N->right);
}
struct node* insert(struct node* node, int key)
{
/* 1. Perform the normal BST rotation */
if (node == NULL)
return(newNode(key));
if (key < node->key)
node->left = insert(node->left, key);
else
node->right = insert(node->right, key);
/* 2. Update height of this ancestor node */
node->height = max(height(node->left), height(node->right)) + 1;
/* 3. Get the balance factor of this ancestor node to check whether
this node became unbalanced */
int balance = getBalance(node);
// If this node becomes unbalanced, then there are 4 cases
// Left Left Case
if (balance > 1 && key < node->left->key)
return rightRotate(node);
// Right Right Case
if (balance < -1 && key > node->right->key)
return leftRotate(node);
// Left Right Case
if (balance > 1 && key > node->left->key)
{
node->left = leftRotate(node->left);
return rightRotate(node);
}
// Right Left Case
if (balance < -1 && key < node->right->key)
{
node->right = rightRotate(node->right);
return leftRotate(node);
}
/* 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;
}
struct node* deleteNode(struct node* root, int key)
{
// STEP 1: PERFORM STANDARD BST DELETE
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) || (root->right == NULL) )
{
struct node *temp = root->left ? root->left : root->right;
// No child case
if(temp == NULL)
{
temp = root;
root = NULL;
}
else // One child case
*root = *temp; // Copy the contents of the non-empty child
free(temp);
}
else
{
// node with two children: Get the inorder successor (smallest
// in the right subtree)
struct node* temp = minValueNode(root->right);
// Copy the inorder successor's data to this node
root->key = temp->key;
// Delete the inorder successor
root->right = deleteNode(root->right, temp->key);
}
}
// If the tree had only one node then return
if (root == NULL)
return root;
// STEP 2: UPDATE HEIGHT OF THE CURRENT NODE
root->height = max(height(root->left), height(root->right)) + 1;
// STEP 3: GET THE BALANCE FACTOR OF THIS NODE (to check whether
// this node became unbalanced)
int balance = getBalance(root);
// If this node becomes unbalanced, then there are 4 cases
// Left Left Case
if (balance > 1 && getBalance(root->left) >= 0)
return rightRotate(root);
// Left Right Case
if (balance > 1 && getBalance(root->left) < 0)
{
root->left = leftRotate(root->left);
return rightRotate(root);
}
// Right Right Case
if (balance < -1 && getBalance(root->right) <= 0)
return leftRotate(root);
// Right Left Case
if (balance < -1 && getBalance(root->right) > 0)
{
root->right = rightRotate(root->right);
return leftRotate(root);
}
return root;
}
// A utility function to print preorder traversal of the tree.
// The function also prints height of every node
void preOrder(struct node *root)
{
if(root != NULL)
{
preOrder(root->left);
printf("%d ", root->key);
preOrder(root->right);
}
}
/* Drier program to test above function*/
int main()
{
struct node *root = NULL;
/* Constructing tree given in the above figure */
root = insert(root, 9);
root = insert(root, 5);
root = insert(root, 10);
root = insert(root, 0);
root = insert(root, 6);
root = insert(root, 11);
root = insert(root, -1);
root = insert(root, 1);
root = insert(root, 2);
root = insert(root, 10);
printf("Pre order traversal of the constructed AVL tree is \n");
preOrder(root);
root = deleteNode(root, 10);
printf("\nPre order traversal after deletion of 10 \n");
preOrder(root);
return 0;
}
How can i print an element when I give a certain position?
example:
root = insert(root, 100); (add 100)
root = insert(root, 300); (add 300)
root = insert(root, 200); (add 200)
root = insert(root, 200); (add 400)
PRINT 1 -> Should print the first element (sorted). Which is 100
PRINT 3 -> Should print the third element (sorted). Which is 300
How can I implement this PRINT on my AVL Tree?
I tried to modify this function but i did not succeed
void preOrder(struct node *root)
{
if(root != NULL)
{
preOrder(root->left);
printf("%d ", root->key);
preOrder(root->right);
}
}
I couldn't use a if statment here to check what values are passing because they are all passed at the same time.
preOrder function will order the numbers. lower to biggest.
I don't understand why you can't modify preOrder to do that - you just have to "remember" that current position an update it along the way:
int findPositionPreOrder(
struct node *root,
int targetPos,
int curPos)
{
if(root != NULL)
{
int newPos = findPositionPreOrder(root->left, targetPos, curPos);
newPos++;
if (newPos == targetPos)
{
printf("%d\n", root->key);
}
return findPositionPreOrder(root->right, targetPos, newPos);
}
else
{
return curPos;
}
}
And you call it like findPositionPreOrder(root, targetPosition, 0);
This is not an optimal solution - you can break the recursion after finding your desired position instead of traversing the rest of the tree.

Copying a binary tree

When asked to create a copy of the binary tree, I have always been told to use a post order traversal logic to make the copy.
Is it not possible to process the original tree in pre-order or in-order to create a copy?
Any traversal method more optimal than the other?
Post-order way:
NODEPTR Copy(NODEPTR p)
{
if (p == null) return p
NODEPTR left = Copy(p-> left)
NODEPTR right = Copy(p-> right)
NODEPTR root = MakeBT(p->data, left, right) //MakeBT is a helper function that makes a tree
return (root)
}
Pre-order way:
NODEPTR Copy(NODEPTR p)
{
if (p == null) return p
NODEPTR root
root->data = p->data
root-> left = Copy(p-> left)
root-> right = Copy(p-> right)
return (root)
}
In-order way:
NODEPTR Copy(NODEPTR p)
{
if (p == null) return p
NODEPTR left = Copy(p-> left)
NODEPTR root
root-> data = p-> data
root-> left = left
root-> right = Copy(p-> right)
return (root)
}
Here is a cpp program to copy a binary tree(Node) to a new binary tree(NewNode).
#include <iostream>
using namespace std;
class Node{
public:
int val;
Node* left=NULL;
Node* right=NULL;
Node(int val){
this->val=val;
this->right=NULL;
this->left=NULL;
}
void insert(int v){
if(this->left==NULL)
this->left=new Node(v);
else if(this->right==NULL)
this->right=new Node(v);
else
cout<<"impossible to insert the node\n";
}
void print(){
cout<<this->val<<" ";
if(this->left) this->left->print();
if(this->right) this->right->print();
}
};
class NewNode{
public:
int val;
NewNode* left=NULL;
NewNode* right=NULL;
NewNode* parent=NULL;
void print(){
cout<<this->val<<" ";
if(this->left) this->left->print();
if(this->right) this->right->print();
}
};
void copy(Node* original,NewNode* duplicate){
duplicate->val=original->val;
// cout<<duplicate->val<<endl;
if(original->left){
NewNode* newLeft=new NewNode;
newLeft->parent=duplicate;
duplicate->left=newLeft;
// printf("in left copying %d %d %d\n",duplicate->val,duplicate->left,duplicate->parent);
copy(original->left,duplicate->left);
}
if(original->right){
NewNode* newRight=new NewNode;
newRight->parent=duplicate;
duplicate->right=newRight;
// printf("in right copying %d %d %d\n",duplicate->val,duplicate->right,duplicate->parent);
copy(original->right,duplicate->right);
}
}
int main(){
Node root(1);
root.insert(2);
root.insert(3);
printf("%d %d %d\n",root.val,root.left,root.right);
Node* temp=root.left;
temp->insert(4);
temp->insert(5);
printf("%d %d %d\n",temp->val,temp->left,temp->right);
NewNode root2;
copy(&root,&root2);
printf("%d %d %d\n",root2.val,root2.left,root2.right);
NewNode *temp1=root2.left;
printf("%d %d %d\n",temp1->val,temp1->left,temp1->right);
root.print();
cout<<endl;
root2.print();
return 0;
}

Resources