I get unexpected output in the code for the following problem:
Construct a complete (or almost complete) binary tree from given integer array.
Use a linked list representation of a queue.
Complete binary tree is full BT, and all leafs are on the same level.
Almost complete BT doesn't have to be full BT, and all leafs are on the same level.
Example 1: Almost Complete BT
arr[]={10,9,-5,1,2}
Tree:
10
/ \
9 -5
/ \
1 2
Example 2: Complete BT
arr[]={10,9,-5,1,2,7,4}
Tree:
10
/ \
9 -5
/ \ / \
1 2 7 4
Code
#include <stdio.h>
#include <stdlib.h>
typedef struct node_tree
{
int info;
struct node_tree *left,*right;
}TREE_NODE;
typedef struct node_queue
{
TREE_NODE *tn;
struct node_queue *next;
}QUEUE_NODE;
TREE_NODE *newTN(int info)
{
TREE_NODE *newN=(TREE_NODE*)malloc(sizeof(TREE_NODE));
newN->left=newN->right=0;
newN->info=info;
return newN;
}
void push_queueN(QUEUE_NODE **pf,QUEUE_NODE **pr,TREE_NODE *tn)
{
QUEUE_NODE *newQN=(QUEUE_NODE*)malloc(sizeof(QUEUE_NODE));
newQN->tn=tn;
newQN->next=0;
if(*pf==0)
*pf=*pr=newQN;
else
{
(*pr)->next=newQN;
*pr=newQN;
}
}
int pop_queueN(QUEUE_NODE **pf,QUEUE_NODE **pr,TREE_NODE **tn)
{
if(*pf==0)
return 0;
QUEUE_NODE *p=*pf;
*tn=p->tn;
if(*pf==*pr)
*pf=*pr=0;
else
*pf=p->next;
free(p);
return 1;
}
TREE_NODE *complete(int *arr,int n)
{
TREE_NODE *root;
QUEUE_NODE *pf=0,*pr=0;
int check=0,i;
int *p=arr;
if(p==NULL)
root=NULL;
root=newTN(arr[0]);
push_queueN(&pf,&pr,root);
p++;
for(i=0;i<n;i++)
{
TREE_NODE *parent=pf->tn;
if(pop_queueN(&pf,&pr,&parent))
check=1;
else
check=0;
TREE_NODE *leftChild=NULL,*rightChild=NULL;
leftChild=newTN(&p);
push_queueN(&pf,&pr,leftChild);
p++;
if(p)
{
rightChild=newTN(&p);
push_queueN(&pf,&pr,rightChild);
p++;
}
parent->left=leftChild;
parent->right=rightChild;
}
return root;
}
int height(TREE_NODE *root)
{
if(root==0)
return 0;
int hl=height(root->left);
int hr=height(root->right);
return 1+(hl>hr?hl:hr);
}
void printCurrLevel(TREE_NODE *root,int level)
{
if(root==0)
return;
if(level==1)
printf("%d",root->info);
else if(level>1)
{
printCurrLevel(root->left,level-1);
printCurrLevel(root->right,level-1);
}
}
void levelOrder(TREE_NODE *root)
{
int h=height(root),i;
for(i=1;i<=h;i++)
printCurrLevel(root,i);
}
int main()
{
int arr[]={10,9,-5,1,2};
int n=sizeof(arr)/sizeof(arr[0]);
TREE_NODE *root;
root=complete(arr,n);
levelOrder(root);
return 0;
}
There are some issues with pointers in function complete().
Could someone point out where are the possible errors?
Related
This question already has answers here:
Wrong output while running C code [duplicate]
(8 answers)
Closed 5 years ago.
I came across some problems while doing my assignment. Part of this assignment involves creating a linked-list with the data given and printing them out. The data stored in the list is of datatype 'Atom', which can be an integer, a string, a "pair"(self-defined datatype), or a list made of Nodes.
If the input is (the first integer indicates the number of data)
4
1 2 3 4
it prints
1 2 3 4
What makes me feel strange is that, if I change the function read_list_helper(int n) like this
Node* read_list_helper(int n)
{
Atom *atom;
if (n == 0) return NULL;
return combine_atom_and_list(get_atom(), read_list_helper(n - 1));
}
the output becomes
4 3 2 1
Why would this happen? I have tried several keywords to search for the answer, but none of them works.
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define STRING 0
#define NUM 1
#define PAIR 2
#define LIST 3
struct Atom;
typedef struct Pair
{
struct Atom *left;
struct Atom *right;
} Pair;
typedef struct Node
{
struct Atom *data;
struct Node *next;
} Node;
typedef struct Atom
{
int dtype;
int val = 0;
char str[21] = {'\0'};
Pair *pair = NULL;
Node *Node = NULL;
} Atom;
Node* read_list();
Node* read_list_helper(int);
Atom* get_atom();
Node* combine_atom_and_list(Atom*, Node*);
void print_atom(Atom*);
void print_pair(Pair*);
void print_list(Node*);
int main()
{
Node *head1;
head1 = read_list();
print_list(head1);
system("pause");
return 0;
}
Node* read_list()
{
int n;
scanf("%d", &n);
return read_list_helper(n);
}
Node* read_list_helper(int n)
{
Atom *atom;
if (n == 0) return NULL;
atom = get_atom();
return combine_atom_and_list(atom, read_list_helper(n - 1));
}
Atom* get_atom()
{
int num;
char str[21];
int i;
Atom* res = (Atom*)malloc(sizeof(Atom));
if (scanf("%d", &num) == 1)
{
res->dtype = NUM;
res->val = num;
}
else
{
scanf(" %20s", str);
res->dtype = STRING;
strncpy(res->str, str, 20);
}
return res;
}
Node* combine_atom_and_list(Atom* atom, Node* node)
{
Node *res = (Node*)malloc(sizeof(Node));
res->data = atom;
res->next = node;
return res;
}
void print_atom(Atom* atom)
{
if (atom == NULL) return;
switch (atom->dtype)
{
case NUM:
printf("%d", atom->val);
break;
case STRING:
printf("%s", atom->str);
break;
case PAIR:
print_pair(atom->pair);
break;
case LIST:
print_list(atom->Node);
break;
default:
break;
}
}
void print_pair(Pair* pair)
{
print_atom(pair->left);
print_atom(pair->right);
}
void print_list(Node* node)
{
print_atom(node->data);
if (node->next != NULL)
{
printf(" ");
print_list(node->next);
}
}
Function arguments are not evaluated in any particular order. Since one of your arguments does I/O, the order of evaluation affects the order of the inputs.
I wanna write a program about linked list that gets a number and if the number was equal to the one of the nodes' data , gives the number of that node .
like the datas in 3 nodes are
123
56
78
and it gets a number like 56 and its equal to the second node's data so the output should be 2.
#include<stdio.h>
#include<stdlib.h>
struct node{
int data;
node *next;
};
node* cnode();
void find(node *first,int i,int d);
int main()
{
node *first,*last;
int n,i,x,d;
printf(" How many nodes ?\t");
scanf("%d",&x);
for(i=1;i<=x;i++){
last=cnode();
last->next=first;
first=last;
}
printf("\n enter a particular data:\t");
scanf("%d",&d);
printf("\n number of the particular node:\t");
find(first,i,d);
}
void find(node *first,int i,int d){
int count=0;
while (first != NULL)
{
if (first->data == d)
count++;
first = first->next;
}
if(count != 0){
printf("%d",count);
}
if(count == 0){
printf("\n NOT FOUND ! ");
}
}
According to the C Standard the function main without parameters shall be declared like
int main( void )
Secondly this declaration of the structure
struct node{
int data;
node *next;
};
is not a valid C declaration.
You should write
struct node{
int data;
struct node *next;
};
typedef struct node node;
or
typedef struct node{
int data;
struct node *next;
} node;
You have to initialize at least node first with NULL. Otherwise the program will have undefined behavior.
node *first = NULL,*last;
The parameter i is not used within the function find. So it may be removed.
void find(node *first, int d);
The function definition can look at least like
void find( node *first, int d )
{
int count = 0;
while ( first != NULL && first->data != d )
{
first = first->next;
++count;
}
if ( first != NULL )
{
printf("%d",count);
}
else
{
printf("\n NOT FOUND ! ");
}
}
Edit : the code works with this edit but I don't understand as to why it does.
working ideone with edit : http://ideone.com/ESfkrs
Edited code :
typedef struct _q{
int front,rear;
tree *a[MAX];
}queue;
void enqueue(queue *q, tree *x){
if(!q || q->rear==MAX-1 || !x){
return;
}
q->a[++q->rear]=x;
}
tree* dequeue(queue *q){
if(q->front>q->rear || q->front==MAX){
return NULL;
}
return q->a[q->front++];
}
I'v following code for creating a BT out of an array representation.
problem is that in multiple loops of while 1 level of BT nodes don't point to next level. i.e r->l & r->r is lost in transition of loop although the mem is heap allocated & must be retained until the program exits.
I'v spent umpteen hours digging this but to no vain. TIA.
working ideone : http://ideone.com/O4VKCH
output :
5 10 20
5 10 20
5 10 20
5 10 20
5 10 20
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 100
typedef struct _tree{
int data;
struct _tree *l,*r;
}tree;
typedef struct _q{
int front,rear;
tree a[MAX];
}queue;
void create_node(tree **rooty,int data){
(*rooty) = (tree*)calloc(1,sizeof(tree));
(*rooty)->data=data;
return;
}
void create_node_bst(tree **rooty,int data){
if(!(*rooty)) {
create_node(rooty,data);
}
if(data<(*rooty)->data) create_node_bst(&(*rooty)->l,data);
if(data>(*rooty)->data) create_node_bst(&(*rooty)->r,data);
}
void inorder(tree *root){
if(!root) return;
if(root->l) inorder(root->l);
printf("%d\t",root->data);
if(root->r) inorder(root->r);
}
void enqueue(queue *q, tree *x){
if(!q || q->rear==MAX-1 || !x){
return;
}
q->a[++q->rear]=*x;
}
tree* dequeue(queue *q){
if(q->front>q->rear || q->front==MAX){
return NULL;
}
return &(q->a[q->front++]);
}
void print_q(queue *q){
if(!q || q->front>q->rear){
return;
}
int front=q->front;
printf("+\n");
while(front<=q->rear){
printf("%d\t",q->a[front++].data);
}
printf("\n-");
}
void bfs_order(tree *root, queue *q){
if(!root || !q){
return;
}
printf("%d\t",root->data);
if(root->l)enqueue(q,root->l);
if(root->r)enqueue(q,root->r);
bfs_order(dequeue(q),q);
}
void initialise_q(queue **q){
if(!*q){
*q = (queue*)malloc(sizeof(queue));
(*q)->front=0;
(*q)->rear=-1;
memset((*q)->a,0,MAX*sizeof(int));
}
}
tree* create_bt(tree *r, queue *q, int *arr, int len){
if(!q || !arr) return NULL;
int i=0,first=1;
tree *root=NULL, *ret=NULL;
while(i<len){
tree *temp_l=NULL, *temp_r=NULL;
root = dequeue(q);
if(first){
ret = root;
first = 0;
}
if(!root) break;
if(i+1<len) {
create_node(&temp_l,arr[i+1]);
enqueue(q,temp_l);
}
if(i+2<len) {
create_node(&temp_r,arr[i+2]);
enqueue(q,temp_r);
}
if(temp_l) {
//root->l=temp_l;
create_node(&(root->l),temp_l->data); <-- Pls focus here
}
if(temp_r) {
//root->l=temp_r;
create_node(&(root->r),temp_r->data); <-- llly, here.
}
inorder(ret); printf("\n"); <-- to demo the output
i+=2;
}
return ret;
}
int main(void) {
tree *root = NULL, *temp_t=NULL;
int arr[]={10,5,20,2,7,8,9,0,1};
int len = sizeof(arr)/sizeof(arr[0]);
for(int k=0;k<len;k++){
//create_node_bst(&root,arr[k]);
}
queue *q = NULL, *temp_q=NULL;
initialise_q(&q);
initialise_q(&temp_q);
create_node(&temp_t,arr[0]);
enqueue(q,temp_t);
tree *bt = create_bt(root,q,arr,len);
//bfs_order(bt,temp_q);
if(root) free(root);
if(q) free(q);
return 0;
}
There are lots of C examples by using an array to represent the tree.
However, I'm trying to use a tree(Nodes) for the Binary heap.
I was trying to add the child left and then right. In order to insert the elements in Width-first-Search, I've used a Queue. Is this necessary?
My Queue is using a Node* not a int type. Because, if I put a int in the Queue I must search the position of the Node(more time needed). Is this an appropriate way to built a Binary heap?
During the insertion, there are bubbling up and downs. However, since i have a binary heap and also a Queue. Do I have to match the orders in Queue also?
4.Do I need to search for inserting position like a BST? or do I approach to the address directly by using Queue?
I've learned the theory. However, the codes and structures are unfamiliar.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int left(int a,int b)
{
return (int)(a-floor((float)a/(float)b)*b);
}
typedef struct Node
{
int data;
struct Node* leftNext;
struct Node* rightNext;
}Node;
struct queue
{
Node** data;
int top;
int bottom;
int size;
}typedef Queue;
int push(Queue* Q,Node* input)
{
printf("PUSH : %d\n",input);
//한칸은 비울 것임.
if(left((*Q).top-(*Q).bottom,(*Q).size)==(*Q).size-1)
{
printf("큐가 다 찼습니다.\n");
return 0;
}
else
{
//큐의 크기를 넘으면 아래로 이동
if((*Q).top==(*Q).size)
(*Q).top=0;
printf("TOP : %d\n",(*Q).top);
(*Q).data[(*Q).top++]=input;
return 1;
}
}
Node* pop(Queue* Q)
{
if(left((*Q).top-(*Q).bottom,(*Q).size)==0)
printf("큐가 비었습니다.\n");
else
{
if((*Q).bottom==(*Q).size)
(*Q).bottom=0;
printf("BOTTOM : %d\n",(*Q).bottom);
return (*Q).data[(*Q).bottom];
}
}
typedef struct Heap
{
Node* head;
}Heap;
int insert(Node** head,int data,Queue* Q)
{
if((*head)!=NULL)
{
if((*head)->leftNext==NULL)
{
(*head)->leftNext=(Node*)malloc(sizeof(Node));
(*head)->leftNext->data=data;
(*head)->leftNext->leftNext=NULL;
(*head)->leftNext->rightNext=NULL;
push(Q,&(*head)->leftNext);
}
else if((*head)->rightNext==NULL)
{
(*head)->rightNext=(Node*)malloc(sizeof(Node));
(*head)->rightNext->data=data;
(*head)->rightNext->leftNext=NULL;
(*head)->rightNext->rightNext=NULL;
push(Q,&(*head)->rightNext);
(*Q).bottom++;
}
else
{
if(insert((pop(Q)),data,Q)==1)
return 1;
else
return 0;
}
}
else
{
printf("헤드가 비었습니다.");
return 0;
}
return 1;
}
int main()
{
//입력 15 6 12 7 10 17
Heap h;
//큐 초기화
Queue Q;
//큐 크기
int temp=100;
Q.data=(Node**)malloc(sizeof(Node*)*temp);
Q.size=temp;
Q.top=0;
Q.bottom=0;
h.head=(Node*)malloc(sizeof(Node));
h.head->data=15;
h.head->leftNext=NULL;
h.head->rightNext=NULL;
insert(&(h.head),6,&Q);
insert(&(h.head),12,&Q);
insert(&(h.head),7,&Q);
insert(&(h.head),10,&Q);
insert(&(h.head),17,&Q);
return 0;
}
This exercise is not really new to me, but it still is quite advance for me. Being a student, I would like to kindly ask for your help regarding this matter.
I need to understand, not just know, how AVL node deletion works. I've been given this C code that I have to complete to demonstrate how AVL insertion and deletion happens. I've done the basics. It's just the balancing and the rotation that got me dizzy.
Here's the main C file:
#include<stdio.h>
#include<stdlib.h>
#include "avl.h"
#define N 10
#define BALANCED 0
#define LEFT_LEANING 1
#define RIGHT_LEANING 2
int main(){
AVL *root=NULL;
int choice=0,x;
while((choice=menu())!=3){
printf("Value: ");
scanf("%i",&x);
switch(choice){
case 1: insert_value(&root,x);
view(root,2);
break;
case 2: delete_value(&root,x);
view(root,2);
}
}
}
here's the avl header file:
#define N 10
#define BALANCED 0
#define LEFT_LEANING 1
#define RIGHT_LEANING 2
//structure for an avl_node
typedef struct node_tag{
int x, height;
struct node_tag *parent;
struct node_tag *left;
struct node_tag *right;
}avl_node;
//print menu and get user choice
int menu(){
int choice;
printf("\n MENU ");
printf("\n[1] - Insert");
printf("\n[2] - Delete");
printf("\n[3] - Exit");
printf("\nYour choice: ");
scanf("%i",&choice);
return choice;
}
//find maximum of 2 numbers
int max(int a,int b){
return(a>b?a:b);
}
//finds the minimum value of the BST
avl_node* minimum(avl_node *rootptr){
if(rootptr!=NULL){
while(rootptr->left!=NULL) rootptr=rootptr->left;
}
return (rootptr);
}
//update height of a given node
void updateheight(avl_node *temp){
if(temp!=NULL)
temp->height = max(temp->left==NULL?-1:temp->left->height,temp->right==NULL?-1:temp->right->height)+1;
}
//left rotate the subtree
void left_rotate(avl_node **rootptr){
}
//right rotate the subtree
void right_rotate(avl_node **rootptr){
}
//determine rotation of node/s
void insert_fixup(avl_node **rootptr, avl_node *temp){
}
//insert value and create node
void insert_value(avl_node **rootptr, int x){
avl_node *temp;
temp = (avl_node *)malloc(sizeof(avl_node));
temp->x = x;
temp->height = 0;
temp->parent = temp->left = temp->right = NULL;
insert_node(rootptr,temp);
insert_fixup(rootptr,temp);
}
void view(avl_node *root, int tabs){
int i;
if(root != NULL){
view(root->right,tabs + 1);
for(i=0;i<tabs;i++) printf("\t");
printf("%2i\n",root->x);
view(root->left,tabs+1);
}
}//view the AVL
void swap(int *a, int *b){
int temp;
temp = *a; *a = *b; *b = temp;
}//swap values
//look for the successor of a node
avl_node* successor(avl_node *rootptr){
if(rootptr==NULL) return (rootptr);
else if(rootptr->right!=NULL) return (minimum(rootptr->right));
while(rootptr->parent!=NULL){
if(rootptr==rootptr->parent->right) rootptr=rootptr->parent;
else break;
}
return (rootptr->parent);
}
//function for searching the location of the node
avl_node* search(avl_node *root,int x){
if(root==NULL || root->x==x) return root;
else{
if(root->x>x) return(search(root->left,x));
else return(search(root->right,x));
}
}
//function for searching the value of the node
int search_node(avl_node *root, int x){
if(root==NULL) return 0;
if(root->x==x) return 1;
else{
if(root->x>x) return(search_node(root->left,x));
else return(search_node(root->right,x));
}
}
//function for deleting a node
void delete_value(avl_node** root,int x){
}
To understand, You should go through the Wiki Page and also try to understand pseudo code to understand node insertion and deletion in AVL tree. Also you can go through Presentation PPT to understand AVL tree. And to find status of your node from tree you can use search() function.