my code creates undifined behaviour when I remove cout<<endl; - c++11

this is my header
/**
* Title: Trees
* Description: NgramTree class to count and store ngrams in a given string
*/
#ifndef NGRAMTREE_H
#define NGRAMTREE_H
#include <iostream>
#include <string>
using namespace std;
typedef string TreeItemType;
struct TreeNode {
TreeItemType item;
TreeNode *leftChildPtr, *rightChildPtr;
int count;
};
// NgramTree.h
class NgramTree {
public:
NgramTree();
~NgramTree();
void addNgram( string ngram );
int getTotalNgramCount();
bool isComplete();
bool isFull();
bool isFull(TreeNode* curr);
void generateTree( string fileName, int n );
ostream& print_recursive( ostream &out, TreeNode *curr );
ostream& print( ostream &out );
private:
// ...
TreeNode *root;
friend ostream& operator<<( ostream& out, NgramTree &tree );
void destroyTree(TreeNode *& treePtr);
int getTotalNgramCount(TreeNode *node);
};
#endif
this is the cpp
/**
* Title: Trees
* Assignment: 2
* Description: implementation of NgramTree class
*/
#include "NgramTree.h"
//empty constructor
NgramTree::NgramTree():root(NULL){};
//destructor
NgramTree::~NgramTree(){
destroyTree(root);
}
bool NgramTree::isFull(){
return isFull(root);
}
bool NgramTree::isFull(TreeNode* curr){
if(curr->leftChildPtr != NULL && curr->rightChildPtr != NULL ){
return isFull(curr->leftChildPtr) && isFull(curr->rightChildPtr);
}
// on leaf node
else if( curr->leftChildPtr == NULL && curr->rightChildPtr == NULL ){
return true;
}
else if( curr == NULL ){
return true;
}
//ever other condition
return false;
}
void NgramTree::addNgram( string ngram ){
if(root == NULL){
cout<<endl;
TreeNode *tmp = new TreeNode;
tmp->item = ngram;
tmp->count = 1;
root = tmp;
return;
}
for( TreeNode *curr = root; curr != NULL; ){
if( ngram.compare(curr->item) == 0){
curr->count++;
return;
}
else if( ngram.compare(curr->item) < 0 ){
// if the node is leaf or node has just right child we have to add ngram to the leftChildPtr
if( curr->leftChildPtr == NULL ){
TreeNode *tmp = new TreeNode;
tmp->item = ngram;
tmp->count = 1;
tmp->leftChildPtr = NULL;
tmp->rightChildPtr = NULL;
curr->leftChildPtr = tmp;
return;
}
else{
curr = curr->leftChildPtr;
}
}
else if( ngram.compare(curr->item) > 0 ){
// if the node is leaf or node has just left child we have to add ngram to //the leftChildPtr
if( curr->rightChildPtr == NULL ){
TreeNode *tmp = new TreeNode;
tmp->item = ngram;
tmp->count = 1;
tmp->leftChildPtr = NULL;
tmp->rightChildPtr = NULL;
curr->rightChildPtr = tmp;
return;
}
else{
curr = curr->rightChildPtr;
}
}
}
}
void NgramTree::generateTree( string fileName, int n ){
string s;
s = "";
//first loop to find words
for(size_t i = 0; i < fileName.length(); ++i){
if(fileName[i] != ' '){
s += fileName[i];
}
//after a word end there is a ' '
if(fileName[i] == ' ' || i == fileName.length()-1 ){
for(size_t j = 0; j <= s.length() - n; ++j ){
addNgram( s.substr(j,n) );
}
s = "";
}
}
}
int NgramTree::getTotalNgramCount(){
return getTotalNgramCount(root);
}
int NgramTree::getTotalNgramCount(TreeNode *node){
if( node != NULL){
// total count is node->count + count(leftSubTree) + count(rightSubTree)
return node->count
+ getTotalNgramCount(node->leftChildPtr)
+ getTotalNgramCount(node->rightChildPtr);
}
else{
return 0;
}
}
void NgramTree::destroyTree(TreeNode *&treePtr){
if (treePtr != NULL){
destroyTree(treePtr->leftChildPtr);
destroyTree(treePtr->rightChildPtr);
delete treePtr;
treePtr = NULL;
}
}
ostream& NgramTree::print_recursive( ostream &out, TreeNode *curr ) {
if( curr == NULL ) return out;
out<<endl;
out<<"item= "<<curr->item<<", frequency= "<<curr->count;
print_recursive(out, curr->leftChildPtr);
return print_recursive(out, curr->rightChildPtr);
}
ostream& NgramTree::print( ostream &out ){
TreeNode *tmp = root;
return print_recursive(out, tmp);
}
ostream& operator<<( ostream& out, NgramTree &tree ){
return tree.print(out);
}
int main(){
NgramTree t;
string s1 = "berkan naber";
int n1 = 3;
t.generateTree(s1, n1);
cout<<t.getTotalNgramCount();
cout<<t<<endl;
return 0;
}
when I remove cout<<endl from void NgramTree::addNgram( string ngram ) method I get undifined behaviour. I removed it and added in different line and it worked again. I also added it before the if statement and it worked again. What cout<<endl might change in method is it releated to function call stack may be? I am not even sure that the problem comes from this method? I am open to solutions that offering somthing to put instead of cout<<endl; which doesn't affect the terminal output unlike cout<<endl.

Related

Find the Error or memory leak

I was writing LinkedList Program in C++
Here is the Code. Find the Error and Memory Leak or anything else.
I want to write a perfect code.
#ifndef LEARN_REVERSELINKLIST_H
#define LEARN_REVERSELINKLIST_H
#include <string>
#include <utility>
#include <iostream>
#include <boost/assert.hpp>
class ReverseLinkList {
private:
struct Node {
std::string string;
Node *Previous{};
Node *Next{};
};
Node *head;
Node *tail;
int count;
public:
ReverseLinkList();
~ReverseLinkList();
void insert(std::string string);
void insertAt(std::string string, int position);
void iterator() const;
void reverseIterator() const;
void remove(const std::string &string);
void removeAt(int position);
int size() const;
Node *getHead() const;
Node *getTail() const;
};
#endif //LEARN_REVERSELINKLIST_H
and Here is the CC File
#include "ReverseLinkList.h"
ReverseLinkList::~ReverseLinkList() {
if (count != 0) {
Node *temp = head;
while (temp != tail->Next) {
delete temp->Previous;
temp = temp->Next;
}
tail = nullptr;
head = nullptr;
}
}
ReverseLinkList::ReverseLinkList()
: head(nullptr), tail(nullptr), count(0) {
}
void ReverseLinkList::iterator() const {
BOOST_ASSERT_MSG(count != 0, "List is empty");
Node *temp;
temp = head;
while (temp != tail->Next) {
std::cout << temp->string << std::endl;
temp = temp->Next;
}
}
void ReverseLinkList::reverseIterator() const {
BOOST_ASSERT_MSG(count != 0, "List is empty");
Node *temp;
temp = tail;
while (temp != head->Previous) {
std::cout << temp->string << std::endl;
temp = temp->Previous;
}
}
void ReverseLinkList::insert(std::string string) {
auto *newNode = new Node;
newNode->string = std::move(string);
count++;
if (head == nullptr && tail == nullptr) {
newNode->Previous = nullptr;
newNode->Next = nullptr;
head = newNode;
tail = newNode;
} else {
tail->Next = newNode;
newNode->Next = nullptr;
newNode->Previous = tail;
tail = newNode;
}
}
int ReverseLinkList::size() const {
return count;
}
void ReverseLinkList::remove(const std::string &string) {
BOOST_ASSERT_MSG(count != 0, "List is empty");
if (count == 1) {
if (head->string == string) {
delete head;
head = nullptr;
tail = nullptr;
}
count--;
return;
}
if (head->string == string) {
Node *temp;
temp = head->Next;
delete head;
head = temp;
head->Previous = nullptr;
count--;
return;
}
if (tail->string == string) {
Node *temp;
temp = tail->Previous;
delete tail;
tail = temp;
temp->Next = nullptr;
count--;
return;
}
Node *temp;
temp = head;
bool verbose = true;
while (temp != tail->Next) {
if (temp->string == string) {
verbose = false;
break;
}
temp = temp->Next;
}
if (verbose) {
std::cerr << "Node not present" << std::endl;
return;
}
Node *previous, *next;
previous = temp->Previous;
next = temp->Next;
delete temp;
previous->Next = next;
next->Previous = previous;
count--;
}
void ReverseLinkList::insertAt(std::string string, int position) {
if (position > count)
return;
if (position == 0) {
if (head == nullptr) {
insert(string);
return;
}
auto *newNode = new Node;
newNode->string = string;
newNode->Previous = nullptr;
head->Previous = newNode;
newNode->Next = head;
head = newNode;
count++;
return;
}
if (position == count - 1) {
insert(string);
return;
}
Node *temp;
temp = head;
while (position != 0) {
temp = temp->Next;
position--;
}
Node *next;
next = temp->Next;
auto *newNode = new Node;
newNode->string = string;
temp->Next = newNode;
newNode->Previous = temp;
newNode->Next = next;
next->Previous = newNode;
count++;
}
ReverseLinkList::Node *ReverseLinkList::getHead() const {
return head;
}
ReverseLinkList::Node *ReverseLinkList::getTail() const {
return tail;
}
void ReverseLinkList::removeAt(int position) {
BOOST_ASSERT_MSG(count != 0, "List is empty");
if (position > count)
return;
Node *temp;
if (count == 1) {
delete head;
head = nullptr;
tail = nullptr;
count--;
return;
}
if (position == 0) {
temp = head->Next;
delete head;
head = temp;
head->Previous = nullptr;
count--;
return;
}
if (position == count) {
temp = tail->Previous;
delete tail;
tail = temp;
tail->Next = nullptr;
count--;
return;
}
temp = head;
while (position != 0) {
temp = temp->Next;
position--;
}
Node *previous;
Node *next;
previous = temp->Previous;
next = temp->Next;
delete temp;
previous->Next = next;
next->Previous = previous;
count--;
}
I would like to have some suggestion how can I write better code and Implement it. If you have some functions you would like to add please do post.
My next move is to make this code using templates

Sub-sequence of Vowels

I was practicing for an interview and came across this question on a website:
A magical sub-sequence of a string S is a sub-sequence of S that
contains all five vowels in order. Find the length of largest magical sub-sequence of a string S.
For example, if S = aeeiooua, then aeiou and aeeioou are magical sub-sequences
but aeio and aeeioua are not.
I am a beginner in dynamic programming and am finding it hard to come up with a recursive formula for this.
I did it with an iterative approach rather than recursive one. I started building solution similar to LIS (Longest Increasing Subsequence) and then optimised it upto O(n).
#include<iostream>
#include<string>
#include<vector>
using namespace std;
string vowel = "aeiou";
int vpos(char c)
{
for (int i = 0; i < 5; ++i)
if (c == vowel[i])
return i;
return -1;
}
int magical(string s)
{
int l = s.length();
int previndex[5] = {-1, -1, -1, -1, -1}; // for each vowel
vector<int> len (l, 0);
int i = 0, maxlen = 0;
// finding first 'a'
while (s[i] != 'a')
{
++i;
if (i == l)
return 0;
}
previndex[0] = i; //prev index of 'a'
len[i] = 1;
for ( ++i; i < l; ++i)
{
if (vpos(s[i]) >= 0) // a vowel
{
/* Need to append to longest subsequence on its left, only for this vowel (for any vowels) and
* its previous vowel (if it is not 'a')
This important observation makes it O(n) -- differnet from typical LIS
*/
if (previndex[vpos(s[i])] >= 0)
len[i] = 1+len[previndex[vpos(s[i])]];
previndex[vpos(s[i])] = i;
if (s[i] != 'a')
{
if (previndex[vpos(s[i])-1] >= 0)
len[i] = max(len[i], 1+len[previndex[vpos(s[i])-1]]);
}
maxlen = max(maxlen, len[i]);
}
}
return maxlen;
}
int main()
{
string s = "aaejkioou";
cout << magical(s);
return 0;
}
O(input string length) runtime
import java.util.*;
public class Main {
/*
algo:
keep map of runningLongestSubsequence that ends in each letter. loop through String s. for each char, try appending
to runningLongestSubsequence for that char, as well as to runningLongestSubsequence for preceding char.
update map with whichever results in longer subsequence.
for String s = "ieaeiouiaooeeeaaeiou", final map is:
terminal letter in longest running subsequence-> longest running subsequence
a -> aaaa
e -> aeeeee
i -> aeeeeei
o -> aeeeeeio
u -> aeeeeeiou
naming:
precCharMap - precedingCharMap
runningLongestSubMap - runningLongestSubsequenceMap
*/
public static int longestSubsequence(String s) {
if (s.length() <= 0) throw new IllegalArgumentException();
Map<Character, Character> precCharMap = new HashMap<>();
precCharMap.put('u', 'o');
precCharMap.put('o', 'i');
precCharMap.put('i', 'e');
precCharMap.put('e', 'a');
Map<Character, String> runningLongestSubMap = new HashMap<>();
for (char currChar : s.toCharArray()) {
//get longest subs
String currCharLongestSub;
String precCharLongestSub = null;
if (currChar == 'a') {
currCharLongestSub = runningLongestSubMap.getOrDefault(currChar, "");
} else {
currCharLongestSub = runningLongestSubMap.get(currChar);
char precChar = precCharMap.get(currChar);
precCharLongestSub = runningLongestSubMap.get(precChar);
}
//update running longest subsequence map
if (precCharLongestSub == null && currCharLongestSub != null) {
updateRunningLongestSubMap(currCharLongestSub, currChar, runningLongestSubMap);
} else if (currCharLongestSub == null && precCharLongestSub != null) {
updateRunningLongestSubMap(precCharLongestSub, currChar, runningLongestSubMap);
} else if (currCharLongestSub != null && precCharLongestSub != null) {
//pick longer
if (currCharLongestSub.length() < precCharLongestSub.length()) {
updateRunningLongestSubMap(precCharLongestSub, currChar, runningLongestSubMap);
} else {
updateRunningLongestSubMap(currCharLongestSub, currChar, runningLongestSubMap);
}
}
}
if (runningLongestSubMap.get('u') == null) {
return 0;
}
return runningLongestSubMap.get('u').length();
}
private static void updateRunningLongestSubMap(String longestSub, char currChar,
Map<Character, String> runningLongestSubMap) {
String currCharLongestSub = longestSub + currChar;
runningLongestSubMap.put(currChar, currCharLongestSub);
}
public static void main(String[] args) {
//String s = "aeeiooua"; //7
//String s = "aeiaaioooaauuaeiou"; //10
String s = "ieaeiouiaooeeeaaeiou"; //9
//String s = "ieaeou"; //0
//String s = "ieaeoooo"; //0
//String s = "aeiou"; //5
//if u have String s beginning in "ao", it'll do nothing with o and
//continue on to index 2.
System.out.println(longestSubsequence(s));
}
}
#include <iostream>
#include<string>
#include<cstring>
using namespace std;
unsigned int getcount(string a, unsigned int l,unsigned int r );
int main()
{
std::string a("aaaaaeeeeaaaaiiioooeeeeuuuuuuiiiiiaaaaaaoo"
"oooeeeeiiioooouuuu");
//std::string a("aaaaaeeeeaaaaiiioooeeeeuuuuuuiiiiiaaaaaaoooooeeeeiiioooo");
//std::string a("aaaaaeeeeaaaaiiioooeeeeiiiiiaaaaaaoooooeeeeiiioooo"); //sol0
//std::string a{"aeiou"};
unsigned int len = a.length();
unsigned int i=0,cnt =0,countmax =0;
bool newstring = true;
while(i<len)
{
if(a.at(i) == 'a' && newstring == true)
{
newstring = false;
cnt = getcount(a,i,len);
if(cnt > countmax)
{
countmax = cnt;
cnt = 0;
}
}
else if(a.at(i)!='a')
{
newstring = true;
}
i++;
}
cout<<countmax;
return 0;
}
unsigned int getcount(string a, unsigned int l,unsigned int r )
{
std::string b("aeiou");
unsigned int seq=0,cnt =0;
unsigned int current =l;
bool compstr = false;
while(current<r)
{
if(a.at(current) == b.at(seq))
{
cnt++;
}
else if((seq <= (b.size()-2)) && (a.at(current) == b.at(seq+1)))
{
seq++;
cnt++;
if (seq == 4)
compstr =true;
}
current++;
}
if (compstr == true)
return cnt;
return 0;
}
you can use recursive approach here (this should work for string length upto max int (easily memorization can be used)
public class LMV {
static final int NOT_POSSIBLE = -1000000000;
// if out put is this i.e soln not possible
static int longestSubsequence(String s, char[] c) {
//exit conditions
if(s.length() ==0 || c.length ==0){
return 0;
}
if(s.length() < c.length){
return NOT_POSSIBLE;
}
if(s.length() == c.length){
for(int i=0; i<s.length(); i++){
if(s.charAt(i) !=c [i]){
return NOT_POSSIBLE;
}
}
return s.length();
}
if(s.charAt(0) < c[0]){
// ignore, go ahead with next item
return longestSubsequence(s.substring(1), c);
} else if (s.charAt(0) == c[0]){
// <case 1> include item and start search for next item in chars
// <case 2> include but search for same item again in chars
// <case 3> don't include item
return Math.max(
Math.max( ( 1+longestSubsequence(s.substring(1), Arrays.copyOfRange(c, 1, c.length) ) ),
( 1+longestSubsequence(s.substring(1), c ) ) ),
( longestSubsequence(s.substring(1), c )) );
} else {
//ignore
return longestSubsequence(s.substring(1), c);
}
}
public static void main(String[] args) {
char[] chars = {'a', 'e', 'i', 'o', 'u'};
String s1 = "aeio";
String s2 = "aaeeieou";
String s3 = "aaeeeieiioiiouu";
System.out.println(longestSubsequence(s1, chars));
System.out.println(longestSubsequence(s2, chars));
System.out.println(longestSubsequence(s3, chars));
}
}
int func( char *p)
{
char *temp = p;
char ae[] = {'a','e','i','o','u'};
int size = strlen(p), i = 0;
int chari = 0, count_aeiou=0;
for (i=0;i<=size; i++){
if (temp[i] == ae[chari]) {
count_aeiou++;
}
else if ( temp[i] == ae[chari+1]) {
count_aeiou++;
chari++;
}
}
if (chari == 4 ) {
printf ("Final count : %d ", count_aeiou);
} else {
count_aeiou = 0;
}
return count_aeiou;
}
The solution to retrun the VOWELS count as per the hackerrank challenge.
int findsubwithcontinuousvowel(string str){
int curr=0;
int start=0,len=0,maxlen=0,i=0;
for(i=0;i<str.size();i++){
if(str[i]=='u' && (current[curr]=='u' || (curr+1<5 && current[curr+1]=='u'))){
//len++;
maxlen=max(len+1,maxlen);
}
if(str[i]==current[curr]){
len++;
}
else if(curr+1<5 && str[i]==current[curr+1]){
len++;
curr++;
}
else{
len=0;
curr=0;
if(str[i]=='a'){
len=1;
}
}
}
return maxlen;
}
Check if vowels are available in sequence in isInSequence and process the result on processor.
public class one {
private char[] chars = {'a','e','i','o','u'};
private int a = 0;
private boolean isInSequence(char c){
// check if char is repeating
if (c == chars[a]){
return true;
}
// if vowels are in sequence and just passed by 'a' and so on...
if (c == 'e' && a == 0){
a++;
return true;
}
if (c == 'i' && a == 1){
a++;
return true;
}
if (c == 'o' && a == 2){
a++;
return true;
}
if (c == 'u' && a == 3){
a++;
return true;
}
return false;
}
private char[] processor(char[] arr){
int length = arr.length-1;
int start = 0;
// In case if all chars are vowels, keeping length == arr
char array[] = new char[length];
for (char a : arr){
if (isInSequence(a)){
array[start] = a;
start++;
}
}
return array;
}
public static void main(String args[]){
char[] arr = {'m','a','e','l','x','o','i','o','u','a'};
one o = new one();
System.out.print(o.processor(arr));
}
}
#include <bits/stdc++.h>
#define ios ios::sync_with_stdio(NULL);cin.tie(NULL);cout.tie(NULL);
#define ll unsigned long long
using namespace std;
int main() {
// your code goes here
ios
string s;
cin>>s;
int n=s.length();
int dp[n+1][5]={0};
for(int i=1;i<=n;i++)
{
if(s[i-1]=='a')
{
dp[i][0]=1+dp[i-1][0];
dp[i][1]=dp[i-1][1];
dp[i][2]=dp[i-1][2];
dp[i][3]=dp[i-1][3];
dp[i][4]=dp[i-1][4];
}
else if(s[i-1]=='e')
{dp[i][0]=dp[i-1][0];
if(dp[i-1][0]>0)
{dp[i][1]=1+max(dp[i-1][1],dp[i-1][0]);}
else
dp[i-1][1]=0;
dp[i][2]=dp[i-1][2];
dp[i][3]=dp[i-1][3];
dp[i][4]=dp[i-1][4];
}
else if(s[i-1]=='i')
{dp[i][0]=dp[i-1][0];
if(dp[i-1][1]>0)
{dp[i][2]=1+max(dp[i-1][1],dp[i-1][2]);}
else
dp[i-1][2]=0;
dp[i][1]=dp[i-1][1];
dp[i][3]=dp[i-1][3];
dp[i][4]=dp[i-1][4];
}
else if(s[i-1]=='o')
{dp[i][0]=dp[i-1][0];
if(dp[i-1][2]>0)
{dp[i][3]=1+max(dp[i-1][3],dp[i-1][2]);}
else
dp[i-1][3]=0;
dp[i][2]=dp[i-1][2];
dp[i][1]=dp[i-1][1];
dp[i][4]=dp[i-1][4];
}
else if(s[i-1]=='u')
{dp[i][0]=dp[i-1][0];
if(dp[i-1][3]>0)
{dp[i][4]=1+max(dp[i-1][4],dp[i-1][3]);}
else
dp[i-1][4]=0;
dp[i][1]=dp[i-1][1];
dp[i][3]=dp[i-1][3];
dp[i][2]=dp[i-1][2];
}
else
{
dp[i][0]=dp[i-1][0];
dp[i][1]=dp[i-1][1];
dp[i][2]=dp[i-1][2];
dp[i][3]=dp[i-1][3];
dp[i][4]=dp[i-1][4];
}
}
cout<<dp[n][4];
return 0;
}

Red-Black Tree Deletion Partially Working

I implemented a red black tree in c++ with find, insert and delete. The delete only works for right side nodes and for the root node. I can't figure out why it isn't working for any of the left side nodes. Here is my code:
Node* searchNode(Node* root, int value){
Node* temp = root;
while (temp != NULL){
if (temp->val == value){
return temp;
}
else if (temp->val < value){
temp = temp->right;
}
else if (temp->val > value){
temp = temp->left;
}
}
}
Node* sibling(Node* node){
if ((node == NULL) || (node->parent == NULL)){
return NULL;
}
if (node == node->parent->left){
return node->parent->right;
}
else{
return node->parent->left;
}
}
Node* maxNode(Node* node){
while (node->right != NULL){
node = node->left;
}
return node;
}
void replaceNode(Node* old, Node* new_node){
if (old->parent == NULL){
old = new_node;
}
else{
if (old == old->parent->left){
old->parent->left = new_node;
}
else{
old->parent->right = new_node;
}
}
if (new_node != NULL){
new_node->parent = old->parent;
}
}
void deleteNode(Node* root, int value){
Node* child;
Node* temp = searchNode(root, value);
if (temp == NULL){
return;
}
if (temp->left != NULL&&temp->right != NULL){
Node* pred = maxNode(temp->right);
temp->val = pred->val;
temp = pred;
}
if (temp->left == NULL || temp->right == NULL){
if (temp->right == NULL && temp->left == NULL){
child = temp;
}
else if (temp->right == NULL){
child = temp->left;
}
else{
child = temp->right;
}
}
if (temp->color == 1){
temp->color = child->color;
delete_case1(root, child);
}
replaceNode(temp, child);
delete temp;
}
void delete_case6(Node* root, Node* n)
{
Node *s = sibling(n);
s->color = n->parent->color;
n->parent->color = 1;
if (n == n->parent->left) {
s->right->color = 1;
rotate_left(root, n->parent);
}
else {
s->left->color = 1;
rotate_right(root, n->parent);
}
}
void delete_case5(Node* root, Node* n)
{
Node *s = sibling(n);
if (s->color == 1) {
if ((n == n->parent->left) &&(s->right->color == 1) &&(s->left->color == 0)) {
s->color = 0;
s->left->color = 1;
rotate_right(root, s);
}else if ((n == n->parent->right) &&(s->left->color == 1) &&(s->right->color == 0)) {
s->color = 0;
s->right->color = 1;
rotate_left(root, s);
}
}
delete_case6(root, n);
}
void delete_case4(Node* root, Node* n)
{
Node *s = sibling(n);
if ((n->parent->color == 0) && (s->color == 1) && (s->left->color == 1) && (s->right->color == 1)) {
s->color = 0;
n->parent->color = 1;
}
else{
delete_case5(root, n);
}
}
void delete_case3(Node* root, Node* n){
Node* s = sibling(n);
if ((n->parent->color == 1) &&(s->color == 1) &&(s->left->color == 1) &&(s->right->color == 1)) {
s->color = 0;
delete_case1(root, n->parent);
}
else
delete_case4(root, n);
}
void delete_case2(Node* root, Node* n){
Node *s = sibling(n);
if (s->color == 0){
n->parent->color = 0;
s->color = 1;
if (n == n->parent->left){
rotate_left(root, n->parent);
}
else if (n == n->parent->right){
rotate_right(root, n->parent);
}
}
delete_case3(root, n);
}
void delete_case1(Node* root,Node* n){
if (n->parent != NULL){
delete_case2(root,n);
}
}
void main(){
ABTree* ABtree=new ABTree;
ABtree->root = NULL;
insertTree(ABtree->root, 15);
insertTree(ABtree->root, 8);
insertTree(ABtree->root, 2);
insertTree(ABtree->root, 9);
insertTree(ABtree->root, 10);
insertTree(ABtree->root, 12);
insertTree(ABtree->root, 18);
insertTree(ABtree->root, 25);
insertTree(ABtree->root, 20);
printTree(ABtree->root);
Node* search=searchNode(ABtree->root, 18);
cout << endl;
cout << search->val<<endl;
deleteNode(ABtree->root, 8);
printTree(ABtree->root);
}
For example if i want to delete either 8/9/2 the program crashes at delete_case4 at the if statement.
Thanks in advance!

How to store an array of LinkedList heads in C++?

Given a binary tree, I'm trying to make a linked list of elements for each depth. That makes D lists for depth D. I'm doing a non-recursive implementation and using level order traversal in my C++ code. Though I don't see any error while compilation, I know that my heads are not storing in the array of pointers. Please have a look at my code. Any help or suggestion would be great since I'm new to data structures. Thanks!
#include <iostream>
#include <queue>
using namespace std;
struct BTnode
{
int data;
BTnode* left;
BTnode* right;
};
struct LLnode
{
int data;
LLnode* next;
};
BTnode* newNode(int data)
{
BTnode* node = new BTnode;
node->data = data;
node->left = NULL;
node->right = NULL;
return node;
}
void MakeLL(LLnode* &head, int data)
{
LLnode* temp = new LLnode;
temp->data = data;
if (head == NULL)
{
head = temp;
temp->next = NULL;
}
else
{
temp->next = head;
head = temp;
}
}
LLnode** LevelElementsLinkedlist(BTnode* &root)
{
if (root == NULL)
return NULL;
queue<BTnode*>nodeQ;
nodeQ.push(root);
int level = 0;
LLnode **arr;
while(1)
{
int count = nodeQ.size();
if (count == 0)
break;
LLnode* head = NULL;
arr[level] = head;
level ++;
while (count > 0)
{
BTnode* node = nodeQ.front();
MakeLL(head,node->data);
nodeQ.pop();
if (node->left)
nodeQ.push(node->left);
if (node->right)
nodeQ.push(node->right);
count--;
}
}
return arr;
}
void printLL(LLnode* head)
{
if (head == NULL)
return;
LLnode* temp = head;
while (temp != NULL)
{
cout << temp->data << " ";
temp = temp->next;
}
}
int main()
{
BTnode* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(40);
root->left->right = newNode(5);
root->right->left = newNode(60);
root->right->right = newNode(7);
root->left->left->left = newNode(8);
root->left->left->right = newNode(9);
root->left->right->left = newNode(10);
root->left->right->right = newNode(11);
root->right->left->left = newNode(12);
root->right->left->right = newNode(13);
root->right->right->left = newNode(14);
root->right->right->right = newNode(15);
LLnode** arr = LevelElementsLinkedlist(root);
int n = sizeof(arr)/sizeof(arr[0]);
cout << n;
for (int i = 0; i < n; i++)
{
printLL(arr[i]);
cout << endl;
}
cout << endl;
return 0;
}
There are a few problem that I noticed in your code.
In the function LevelElementsLinkedlist, you are not allocating space for arr. It should be LLnode *arr = new LLnode *[100].
Check the line where you have written the following:
LLnode* head = NULL;
arr[level] = head;
You are assigning NULL to head and then adding it to the array. Your whole array will contain nothing else but NULLs.
Try fixing these issues and try executing your code again.

Trying to insert an Avl tree

I am trying to make an insertion method for an Avl tree but the structure and order of my nodes turns out to be incorrect. I am having trouble finding where i am going wrong.
Here are my methods
Any sort of help would be appreciated
template
void AvL<T>::insert(string val, T k)
{
if (head == NULL) {
head = new AvLNode<T>(val, k);
} else {
put(head, val, k);
}
}
template <class T>
void AvL<T>::put(AvLNode<T>* root,string val,T key1) {
if (root->key > key1) {
if (root->left != NULL) {
put(root->left, val, key1);
Balance(root, key1);
} else {
root->left = new AvLNode<T>(val, key1);
root->bf = nodeHeight(root->left) - nodeHeight(root->right);
root->left->parent = root;
}
} else {
if (root->right != NULL) {
put(root->right, val, key1);
Balance(root, key1);
} else {
root->right = new AvLNode<T>(val, key1);
root->bf = nodeHeight(root->left) - nodeHeight(root->right);
root->right->parent = root;
}
}
}
template<class T>
void AvL<T>::Balance(AvLNode<T>* root, T key1)
{ root->bf = nodeHeight(root->left) - nodeHeight(root->right);
if (root->bf < -1 && key1 > root->right->key) {
cout << "here1 ";
LeftRotate(root);
} else if (root->bf > 1 && key1 < root->left->key) {
cout << "here2 ";
RightRotate(root);
} else if (root->bf < -1 && key1 < root->right->key) {
RightRotate(root->right);
cout << "here3 ";
LeftRotate(root);
} else if (root->bf > 1 && key1 > root->left->key) {
LeftRotate(root->left);
cout << "here4 ";
RightRotate(root);
}
}
template<class T>
void AvL<T>::RightRotate(AvLNode<T>* node)
{
AvLNode<T>* node1 = node->left;
node->left = node1->right;
node1->right = node;
node->bf = nodeHeight(node->left) - nodeHeight(node->right);
node1->bf = nodeHeight(node1->left) - nodeHeight(node1->right);
node = node1;
}
template<class T>
void AvL<T>::LeftRotate(AvLNode<T>* node)
{
AvLNode<T>* node1 = node->right;
node->right = node1->left;
node1->left = node;
node->bf = nodeHeight(node->left) - nodeHeight(node->right);
node1->bf = nodeHeight(node1->left) - nodeHeight(node1->right);
node = node1;
}
template<class T>
int AvL<T>::nodeHeight( AvLNode<T> *n)
{
int lheight=0;
int rheight=0;
int h = 0;
if (n == NULL)
{
return -1;
} else {
lheight = nodeHeight(n->left);
rheight = nodeHeight(n->right);
h = 1+max(lheight,rheight);
return h;
}
}
My .h file
template <class T>
struct AvLNode
{
string value;
T key;
AvLNode *parent; // pointer to parent node
AvLNode *left; // pointer to left child
AvLNode *right; // pointer to right child
int bf; // Balance factor of node
AvLNode(string Val, T k)
{
this->value = Val;
this->key = k;
this->parent = NULL;
this->left = NULL;
this->right = NULL;
bf = 0;
}
};
template <class T>
class AvL
{
AvLNode<T> *head;
public:
// Constructor
AvL();
// Destructor
~AvL();
// Insertion Function
void insert(string val, T k); // inserts the given key value pair into the tree
void Balance(AvLNode<T>* node, T key1);
void delete_node(T k); // deletes the node for the given key
void RightRotate(AvLNode<T>* node);
void LeftRotate(AvLNode<T>* node);
void put(AvLNode<T>* root,string val,T key1);
int nodeHeight(AvLNode<T> *n); // returns height of the subtree from given node
};
Your balance function is wrong. Since you've already inserted your new node into the tree, you don't need to worry about the key any more in Balance() - so the prototype should look like this:
template<class T>
void AvL<T>::Balance(AvLNode<T>* root);
The way you're doing it now seems to be attempting to balance based on the key you just inserted - which isn't necessary! You can balance the tree just based on the balance factors of nodes - here's how.
template<class T>
void AvL<T>::Balance(AvLNode<T>* root) {
if (root->bf > 1) {
if (root->left->bf == -1) LeftRotate(root->left);
RightRotate(root);
} else if (root->bf < -1) {
if (root->right->bf == 1) RightRotate(root->right);
LeftRotate(root);
}
}
You can read more about it here - but you seem to have the idea almost down. The only thing you need to change conceptually is the idea that you're balancing based on the key you just inserted. You're not - you're balancing based on the shape of the tree, which you can get from just the balance factors of each subtree.

Resources