binary search:please tell me whats wrong here - error-handling

I tried binary tree data structure but found it to be not working and giving an error. Please correct my code. Thanks!
It gives warning but with the inputs in main it stops running .
#include<stdlib.h>
#include<stdio.h>
typedef struct
{
int item;
struct node * leftc;
struct node * rightc;
}node;
void create(int key, node **tree )
{
if(*tree ==0)
{
(*tree)= (node *)malloc(sizeof(node *));
(*tree)->item=key;
(*tree)->leftc=((*tree)->rightc)=NULL;
}
else
{
if(key >= (*tree)->item )
{
create(key, &((*tree)->rightc));
}
else if(key<(*tree)->item)
{
create(key, &((*tree)->leftc));
}
}
}
node * search(int key, node * tree)
{
if(tree !=NULL)
{
if(key == tree->item)
return tree;
else if(key > tree->item)
search(key, tree->rightc);
else
search(key, tree->leftc);
}
return NULL;
}
void cut(node * tree)
{
if(tree != NULL)
{
cut(tree->leftc);
cut(tree->rightc);
free(tree);
}
}
void print_preorder(node * tree)
{
if (tree) {
printf("%d\n",tree->item);
print_preorder(tree->leftc);
print_preorder(tree->rightc);
}
}
int main()
{
node * root=NULL;
create(9,&root);
create(16,&root);
create(24,&root);
create(6,&root);
return 0;
}

Change
typedef struct
{
int item;
struct node * leftc;
struct node * rightc;
}node;
to
typedef struct node
{
int item;
struct node * leftc;
struct node * rightc;
}node;
Within your structure you refer to 'struct node' so you need the name in order for it to properly reference itself. Of course, after the typedef then you can just refer to it as node.
The test program compiled and ran fine with the code given otherwise.

I know this doesn't answer your question about the error, but I noticed a major problem with your search() function. You only return the node you're looking for if it's the first one that is put into the function. The recursive calls to search() do not return anything. The function should look something like this:
node * search(int key, node * tree)
{
if (tree !=NULL)
{
if (key == tree->item) {
return tree;
} else if (key > tree->item) {
return search(key, tree->rightc);
} else if (key < tree->item) {
return search(key, tree->leftc);
}
}
return NULL;
}
Also, in your create() function, did you mean to check if (*tree == NULL) instead of if (*tree == 0)?

Related

member access within misaligned address 0x000000000002 for type 'struct ListNode', which requires 8 byte alignment

How can I solve this misaligned address problem.I came across this problem when I try to solve addition of two numbers using linked list in reverse order in LeetCode
ProblemLink:https://leetcode.com/problems/add-two-numbers/
algorithm : Ive created a variable flag to check for carry over.When i tried to add the first element of linked list 1 with the first element of linked list 2 ,its throwing an error.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2){
struct node{
int num;
struct node *ptr;
};
struct node* create(){
struct node *ptr1=malloc(sizeof(struct node));
ptr1->ptr=NULL;
return ptr1;
}
struct node *head=NULL;
struct node *temp=NULL;
int flag=0;
while(l1!=NULL && l2!=NULL){
if(head==NULL){
head=create();
temp=head;
}
else{
temp->ptr=create();
temp=temp->ptr;
}
int a=(l1->val); //showing error
a=a+(l2->val);
a=a+flag;
int b=a%10;
flag=(a-b)/10;
temp->num=b;
l1=l1->val;
l2=l2->val;
}
while(l1==NULL && l2!=NULL){
if(head==NULL){
head=create();
temp=head;
}
else{
temp->ptr=create();
temp=temp->ptr;
}
int a=(l2->val)+flag ;
int b=a%10;
flag=(a-b)/10;
temp->num=b;
l2=l2->val;
}
while(l1!=NULL && l2==NULL){
if(head==NULL){
head=create();
temp=head;
}
else{
temp->ptr=create();
temp=temp->ptr;
}
int a=(l1->val)+flag ;
int b=a%10;
flag=(a-b)/10;
temp->num=b;
l1=l1->val;
}
while(l1==NULL && l2==NULL && flag==1){
if(head==NULL){
head=create();
temp=head;
}
else{
temp->ptr=create();
temp=temp->ptr;
}
temp->num=1;
flag=0;
}
return head;
}

Finding whether the binary tree is valid bst

I get Following error on running the code below for tree(2,2,2) on leetcode:
AddressSanitizer:DEADLYSIGNAL
==31==ERROR: AddressSanitizer: stack-overflow on address 0x7ffe3ba89ff8 (pc 0x000000372df9 bp 0x7ffe3ba8a010 sp 0x7ffe3ba8a000 T0)
==31==ABORTING
My code is given below:
class Solution {
public:
bool isValidBST(TreeNode* root) {
TreeNode* cur=root;
while(cur){
cout<<cur->val<<endl;
if(!cur->left) {
if(!cur->right) return 1;
int a=cur->val,b=cur->right->val;
if(a>=b )
return false;
cur=cur->right;
}
else{
TreeNode* prev=cur->left;
while(prev->right && prev->right!=cur)
prev=prev->right;
if(prev->right==NULL){
prev->right=cur;
cur=cur->left;
}
else{
prev->right=0;
if(cur->val>=cur->right->val) return 0;
cur=cur->right;
}
}
}
return 1;
}
};

BST delete - delete "tmp" causes lose of the tree

debug result
Attached my code for trying to delete a node in bst.
If I want to delete node 1, when specifying tmp = del in "if (del_node->l_ == NULL)", and remove tmp, then del is removed as well, and the tree data is lost. how can I solve this issue?
Example tree:
3
/ \
1 5
\
2
all data members and functions are declared public for simplicity.
void BST::DeleteNode(int data) {
BinaryTreeNode* &del_node = BST_Search(head_, data);
if (!del_node->l_ && !del_node->r_)
{
delete del_node;
del_node = nullptr;
return;
}
if (del_node->l_ == NULL)
{
BinaryTreeNode* tmp = del_node;
del_node = del_node->r_;
tmp = nullptr;
delete tmp;
return;
}
if (del_node->r_ == NULL)
{
BinaryTreeNode* tmp = del_node;
del_node = del_node->l_;
delete tmp;
return;
}
else
{
del_node->data_ = smallestRightSubTree(del_node->r_);
}
}
int BST::smallestRightSubTree(BinaryTreeNode* rightroot)
{
// if rightroot has no more left childs
if (rightroot && !rightroot->l_)
{
int tmpVal = rightroot->data_;
BinaryTreeNode* tmp = rightroot;
rightroot = rightroot->r_;
delete tmp;
return tmpVal;
}
return smallestRightSubTree(rightroot->l_);
}
int main()
{
BST bst;
bst.BST_Insert(bst.head_, 3);
bst.BST_Insert(bst.head_, 5);
bst.BST_Insert(bst.head_, 1);
bst.BST_Insert(bst.head_, 2);
bst.DeleteNode(1);
return 0;
}
Thanks for help!
EDIT: this is how tmp and del_node look like after the line "del_node = del_node->r_)" in the condition "if(del->l = null)"
void BST::BST_Insert(BinaryTreeNode*& head, int data) {
if (head == nullptr) {
head = new BinaryTreeNode(data, nullptr, nullptr);
return;
}
if (data > head->data_) {
BST_Insert(head->r_, data);
}
else {
BST_Insert(head->l_, data);
}
}
BinaryTreeNode* BST::BST_Search(BinaryTreeNode* root, int key) {
if (root == nullptr || root->data_ == key)
return root;
if (key > root->data_)
return BST_Search(root->r_, key);
return BST_Search(root->l_, key);
}
If your BST_Search returns a BinaryTreeNode* by value, what is the reference in BinaryTreeNode* &del_node = BST_Search(head_, data); actually referencing? It allocates a new temporary and references that. You probably wanted it to reference the variable that is holding the pointer in the tree so that you can modify the tree.
Your BST_Search would have to look like this:
BinaryTreeNode*& BST::BST_Search(BinaryTreeNode*& root, int key) {
if (root == nullptr || root->data_ == key)
return root;
if (key > root->data_)
return BST_Search(root->r_, key);
return BST_Search(root->l_, key);
}
I can't check whether this actually works, because you didn't provide a self-contained compilable example. But something along these lines.

How to delete the largest node in Binary search Tree

I am trying to delete the largest node in binary search tree, I thougth that these code below should be able to do it but for some reason it is not. Could someone help please!
public void remove() {
Node current = root;
while(true){
Node parent = current;
current = current.getRighChild();
if (current == null){
parent.setRighChild(null);
return;
}
}
}
public void remove()
{
root = deleteMax(root);
}
private Node deleteMax(Node x ) {
if (x.getRighChild() == null)
{
return x.getLeftChild();
}
x.setRighChild(deleteMax(x.getRighChild()));
return x;
}
In your code if the right node is empty you are still deleting it. Instead of deleting the current if it is the max. Try something like this:
removeLargest() {
current = getRoot();
rightNode == null;
while (root.Right){
current == root.Right
}
if (current.left()){
rotate()
}
current.delete()
}

Infix to Postfix Conversion

I'm trying to code that converts infix expressions to postfix expressions. Currently, the program works correctly if I enter for e.g "5+6" it will output the correct answer which is "5 6 +". The problem occurs when I enter more than one operator for e.g "5+6-3", it outputs and incorrect answer "+3-". Can someone please point out where I'm making the error ? Thanks, in advance !
void main(){
Stack *s = new Stack;
string input;
cout <<"Enter Expression"<<endl;
cin>>input;
InfixToPostfix(input);
system("PAUSE");
}
string InfixToPostfix(string input){
Stack *S = new Stack();
string postfix = "";
for (int i=0; i < input.length();i++){
if (input[i]== ' '||input[i]==',') continue;
else if (IsOperator(input[i]))
{
while(!S->IsStackEmpty() && S->StackTop() != '(' && HasHigherPrecedence(S->StackTop(),input[i]))
{
postfix=S->StackTop();
S->Pop();
}
S->Push(input[i]);
}
else if(IsOperand(input[i]))
{
postfix +=input[i];
}
else if (input[i] == '(')
{
S->Push(input[i]);
}
else if (input[i]==')')
{
while(!S->IsStackEmpty() && S->StackTop() != '('){
postfix += S->StackTop();
S->Pop();
}
S->Pop();
}
}
while(!S->IsStackEmpty()){
postfix +=S->StackTop();
S->Pop();
}
cout <<""<<postfix;
return postfix;
}
bool IsOperand(char C)
{
if(C>= '0' && C<= '9') return true;
if(C>= 'a' && C<= 'z') return true;
if(C>= 'A' && C<= 'Z') return true;
return false;
}
bool IsOperator(char C)
{
if(C=='+' || C== '-' || C =='*' || C == '/' ||C == '$')
{
return true;
}else{
return false;
}
}
int IsRightAssociative(char op)
{
if(op=='$'){
return true;
}else{
return false;
}
}
int GetOperatorWeight(char op){
int weight = -1;
switch(op)
{
case'+':
case '-':
weight=1;
break;
case '*':
case '/':
weight=2;
break;
case '$':
weight=3;
break;
}
return weight;
}
int HasHigherPrecedence ( char op1, char op2)
{
int op1Weight= GetOperatorWeight(op1);
int op2Weight = GetOperatorWeight(op2);
if(op1Weight == op2Weight)
{
if(IsRightAssociative(op1))
{
return false;
}else{
return true;
}
return op1Weight > op2Weight ? true:false;
}
}
One suggestion: use a tree, rather than a stack, as an intermediate data structure. Let the operator with lowest precedence be the root of the tree and build it recursively from there. Then walk through the tree from left to right, again recursively, to generate the postfix version. That way, you can also keep track of the maximum stack depth for the postfix version, which can be important as many hand-held RPN calculators, for example, have very limited stack depths.