I am trying to write a function to get the height of a binary tree. When I print the value of the maxi the value is what I expect but when the function returns the value, the value is always 0. Can someone tell what I am doing wrong here?
int treeHeight(tree *p)
{
static int maxi=0;
static int i=0;
if(p==NULL)
{
return maxi;
}
else
{
if(p->left!=NULL||p->right!=NULL)
{
i++;
}
else
{
i++;
if(maxi<i)
{
maxi=i;
}
}
treeHeight(p->left);
treeHeight(p->right);
i--;
}
}
Your treeHeight function should look like the following:
int treeHeight(tree *p)
{
if (p == NULL)
{
return -1;
}
int left = treeHeight(p->left);
int right = treeHeight(p->right);
return 1 + std::max(left, right);
}
Why do you need to static variables i and maxi there? You don't need those variables there to find out the height of a binary tree.
Related
I'm trying to write a recursive binary search function using below approach. I'm basically using divide and conquer strategy and everything looks good to me in code, but unable to figure out where my code and approach goes wrong.
#include<iostream>
using namespace std;
bool b_search(int *arr, int n, int start, int end){
if(start==end){
if(arr[start]==n){
return true;
}
else{
return false;
}
}
else{
int mid=start+(end-start)/2;
if(arr[mid]==n){
return true;
}
else if(arr[mid]>n){
return b_search(arr,n,mid+1,end);
}
else{
return b_search(arr,n,start,mid-1);
}
}
}
int main(){
int arr[8]={3,5,8,11,13,15,16,25};
cout<<b_search(arr,16,0,7);
}
I'm getting output as zero but it should be 1.
When arr[mid]>n you then search for the number in the part with higher number which is guaranteed to miss. You need to search in the part with lower numbers.
Example:
bool b_search(int *arr, int n, int start, int end) {
if (start == end) return arr[start] == n;
int mid = start + (end - start) / 2;
if (arr[mid] < n) { // arr[mid] is lower than n, search in the high part
return b_search(arr, n, mid + 1, end);
} else if (arr[mid] > n) { // arr[mid] is greater than n, search lower part
return b_search(arr, n, start, mid - 1);
}
return true;
}
Your next interval is wrong.
else if(arr[mid]>n){
return b_search(arr,n,mid+1,end);
When the middle element is too large then you continue with the larger portion of the array. You should continue with the smaller portion of the array instead:
else if(arr[mid]<n){
return b_search(arr,n,mid+1,end);
}
else{
return b_search(arr,n,start,mid-1);
}
You are searching in the wrong direction. If arr[mid] > n then you should be searching from start to mid -1 and the other way around. The reason is that your searched value n is then in the other half of your searched array
#include<iostream>
using namespace std;
bool b_search(int *arr, int n, int start, int end)
{
if(start==end)
{
if(arr[start]==n)
{
return true;
}
else
{
return false;
}
}
else
{
int mid=start+(end-start)/2;
if(arr[mid]==n)
{
return true;
}
else if(arr[mid]<n) // turn around the comparison
{
return b_search(arr,n,mid+1,end);
}
else
{
return b_search(arr,n,start,mid-1);
}
}
}
int main()
{
int arr[8]={3,5,8,11,13,15,16,25};
cout<<b_search(arr,16,0,7);
}
I am required to implement a dynamic array that adjusts, dynamically, in accordance with the number of value (temperatures) that are input into the code. I have written the majority of the code for this to be possible, however I have run into a bug and for the life of me, have been unable to locate the issue.
The program is supposed to output the values of temp_a, make temp_b = temp_a, output the value of temp_b, and then clear the value of temp_a, and finally output the values of temp_b once more.
However, when I compile the program, it outputs that the list is full and cannot add any more values, meaning there is a logic error somewhere in the code.
Please forgive me for the lengthy code, as soon as I can locate the error, the code shall be separated into multiple compilations.
#include <iostream>
using namespace std;
class TemperatureList {
private:
int* temp; // pointer to dynamic array
short current_size; // current number of elements
short max_size; // max number of elements allowed in this list
public:
// Overloading assignment operator
void operator =(const TemperatureList& another_list);
// === Constructors ===
// Default constructor
TemperatureList();
// Constructor that accepts an integer parameter that specifies the max length of the list
TemperatureList(int max);
// Copy constructor that accepts another List as parameter
TemperatureList(const TemperatureList& another_list);
// Destructor
~TemperatureList();
// === Modifier functions ===
// add new_value to end of list if there is still space
void add_temperature(int new_value);
// === Accessor functions ===
// return current current_size of the list
short get_current_size();
// === Other functions ===
// return the last element, or 0 if the list is empty, with a warning output
int get_last();
// return element at the position-th position, or 0 if the list is empty, with a warning output
int get_temp(short position);
// returns if current_size == 0
bool set_temp(short position, int value);
// returns if current_size == 0
bool empty();
// returns if current_size == max_size
bool full();
// Output list separated by commas
friend ostream& operator <<(ostream& outs, const TemperatureList& list);
};
int main() {
TemperatureList temp_a;
temp_a.add_temperature(23.5);
temp_a.add_temperature(24.6);
cout << temp_a;
TemperatureList temp_b = temp_a;
cout << temp_b;
temp_a = TemperatureList();
cout << "Now there's no temperatures in a.\n";
cout << temp_a;
cout << "How about temperatures in b?\n";
cout << temp_b;
return 0;
}
void TemperatureList::operator =(const TemperatureList& another_list) {
delete[] temp;
current_size = another_list.current_size;
max_size = another_list.max_size;
if (current_size > 0) {
temp = new int[max_size];
for (int i = 0; i < max_size; i++) {
temp[i] = another_list.temp[i];
}
}
else {
temp = NULL;
}
}
TemperatureList::TemperatureList() {
current_size = 0;
max_size = 0;
temp = NULL;
}
TemperatureList::TemperatureList(int max) : max_size(max) {
current_size = 0;
temp = new int[max];
}
TemperatureList::TemperatureList(const TemperatureList& another_list) {
current_size = another_list.current_size;
max_size = another_list.max_size;
if (current_size > 0) {
temp = new int[max_size];
for (int i = 0; i < max_size; i++) {
temp[i] = another_list.temp[i];
}
}
else {
temp = NULL;
}
}
TemperatureList::~TemperatureList() {
//cout << "== I am in destructor ==\n";
delete[] temp;
}
void TemperatureList::add_temperature(int new_value) {
if (current_size < max_size) {
temp[current_size] = new_value;
current_size++;
}
else {
cout << "Cannot add value to the list. It is full.\n";
}
}
int TemperatureList::get_last() {
if (empty()) {
cout << "The list is empty\n";
return 0;
}
else {
return temp[current_size - 1];
}
}
int TemperatureList::get_temp(short position) {
if (current_size >= position) {
return temp[position - 1];
}
else {
cout << "There is no temperature\n";
return 0;
}
}
bool TemperatureList::set_temp(short position, int value) {
if (current_size >= position) {
temp[position - 1] = value;
return true;
}
else {
return false;
}
}
short TemperatureList::get_current_size() {
return current_size;
}
bool TemperatureList::empty() {
return (current_size == 0);
}
bool TemperatureList::full() {
return (current_size == max_size);
}
ostream& operator <<(ostream& outs, const TemperatureList& list) {
int i;
for (i = 0; i < (list.current_size - 1); i++) {
outs << list.temp[i] << ",";
}
outs << list.temp[i];
return outs;
}
The logic error seems to stem from the fact that you initialize your current_size and max_size to zero. So, unless your run the overloaded constructor (wherein you’re set the max_size), every call to addTemperature() is going to fail the (current_size < max_size) check because they are both equal to zero.
I am trying to count the number of comparisons done by heap sorting algorithm.
my code is based on priority queue and I want to know where I should put the counter. here is what I have but when I try to print the counter it shows zero counts, what am I doing wrong? Thank you.
here is the heapbuild function:
#include<iostream>
vector<int> pq_keys;
void buildHeap()
{
int size = pq_keys.size();
int midIdx = (size -2)/2;
while (midIdx >= 0)
{
shiftRight(midIdx, size-1);
--midIdx;
}
and this is the function that does the comparison:
int shiftRight(int low, int high)
{
int root = low;
int counter=0;
while ((root*2)+1 <= high)
{
int leftChild = (root * 2) + 1;
int rightChild = leftChild + 1;
int swapIdx = root;
if (pq_keys[swapIdx] < pq_keys[leftChild])
{
counter++;
cout<<counter;
swapIdx = leftChild;
}
/*If right child exists check if it is less than current root*/
if ((rightChild <= high) && (pq_keys[swapIdx] < pq_keys[rightChild]))
{
counter++;
swapIdx = rightChild;
}
/*Make the biggest element of root, left and right child the root*/
if (swapIdx != root)
{
counter++;
int tmp = pq_keys[root];
pq_keys[root] = pq_keys[swapIdx];
pq_keys[swapIdx] = tmp;
root = swapIdx;
}
else
{
break;
}
}
return counter;
}
You want to increment the counter before you do the comparison. Consider this code, from your shiftRight method:
if (pq_keys[swapIdx] < pq_keys[leftChild])
{
counter++;
cout<<counter;
swapIdx = leftChild;
}
That only increments the counter if the conditional is true. If pq_keys[swpIdx] >= pq_keys[leftChild], then you made the comparison without counting it. You need to change your code to be:
counter++;
if (pq_keys[swapIdx] < pq_keys[leftChild])
{
cout<<counter;
swapIdx = leftChild;
}
You need to do the same thing in the other two places where you count comparisons: increment the counter, then do the comparison.
class LessPredicate
{
size_t callCount_ = 0;
temlate<class T>
bool compare(const T& l, conct T& r)
{
return l < r; // or other logic
}
public:
size_t CallTimes() const { return callCount_; }
temlate<class T>
bool operator() (const T& l, conct T& r)
{
++callCount_;
return compare(l, r);
}
};
int main()
{
LessPredicate less;
...// use it like less(a, b) instead a < b;
auto compareCount = less.CallTimes();
}
I have two C++ functions in a class:
void Attribute::setIndex(int inIndex) {
if (inIndex < 0) {
index = 0;
}
else if (inIndex >= MAX_NUM_ATTRIBUTES) {
index = MAX_NUM_ATTRIBUTES - 1;
}
else {
index = inIndex;
}
}
and
int Attribute::getValueWithinRange(int value) {
value = setIndex(value);
return value;
}
The second function is supposed to use setIndex to set 'value' to the correct number and return it. However, since the first function is a void function, i cannot simply pas the value in the way i did above. Should i do pass by reference or are there any suggestions? Thank you very much.
I would like just to note, that if you are learning C++, you should try to learn model cases first, sometimes rushing examples is not the best way, but there we go:
Change the setIndex to return int, my favorite;
int Attribute::setIndex(int inIndex)
{
if (inIndex < 0)
{
index = 0;
}
else if (inIndex >= MAX_NUM_ATTRIBUTES)
{
index = MAX_NUM_ATTRIBUTES - 1;
}
else
{
index = inIndex;
}
return index;
}
int Attribute::getValueWithinRange(int value)
{
value = setIndex(value);
return value;
}
Change the getValueWithinRange to return index, both methods are in one class, they share the access to index;
int Attribute::getValueWithinRange(int value)
{
setIndex(value);
return index;
}
Giving it reference would work, but you can not set reference to null unless using a trick and it would require unnecessarily another method, so pointer makes it less messy:
int Attribute::setIndex(int inIndex, int* ret_index = nullptr)
{
if (inIndex < 0)
{
index = 0;
}
else if (inIndex >= MAX_NUM_ATTRIBUTES)
{
index = MAX_NUM_ATTRIBUTES - 1;
}
else
{
index = inIndex;
}
if (ret_index != nullptr) *ret_index = index;
return index;
}
int Attribute::getValueWithinRange(int value)
{
int retvalue;
setIndex(value); // use it like this when returning value is not needed
setIndex(value, &retvalue);
return retvalue;
}
I've been trying to understand what havn't I initialized in this code and I completely(?) understand what is uninitialized but I don't know how to initialize it.
I am getting the error:
==11931== Conditional jump or move depends on uninitialised value(s)
==11931== at 0x804ABA6: Hashtable<int>::put(int, int) (hash_table.h:169)
==11931== by 0x8048F80: test_put() (hash_table_test.cpp:27)
==11931== by 0x804A551: main (hash_table_test.cpp:52)
==11931== Uninitialised value was created by a heap allocation
==11931== at 0x402ADFC: operator new[](unsigned int) (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==11931== by 0x804A9AE: Hashtable<int>::Hashtable() (hash_table.h:64)
==11931== by 0x8048F62: test_put() (hash_table_test.cpp:26)
==11931== by 0x804A551: main (hash_table_test.cpp:52)
from the valgrind so apparantly I havn't been initializing correctly the c'tor for Hashtable class:
Hashtable() :
ht_keys(2), ht_size(0), dynamicArray(NULL) {
dynamicArray = new Node[ht_keys];
for (int i = 0; i < ht_keys; i++) {
dynamicArray[i].delete_val = false;
dynamicArray[i].key=0;
dynamicArray[i].default_node = false;
}
}
the dynamic array is of type Node* which it's private fields are:
bool delete_val;
T element;
int key;
bool default_node;
the class Node is inside the class Hashtable.
how can I initialize dynamicArray?
here's the full code:
#include <string>
#include <iostream>
#include "library2.h"
#include <iterator>
using namespace std;
#ifndef HASH_TABLE_HPP_
#define HASH_TABLE_HPP_
#define DIV 2
//type T must have c'tor, operator !=
template<class T>
class Hashtable {
public:
class Node {
public:
Node(const T t) :
delete_val(false), element(t), key(0), default_node(true) {
}
Node(bool v, const Node& n) :
delete_val(v), element(n.element), key(0), default_node(
n.default_node) {
}
Node(const Node& n) :
delete_val(false), element(n.element), key(n.key), default_node(
n.default_node) {
}
Node() :
delete_val(false), key(0), default_node(true) {
}
bool operator==(const Node* n) {
if (n) {
if (element != n->element || default_node != n->default_node) {
return false;
}
return true;
}
return false;
}
bool operator!=(const Node n) {
if (!(*this == n)) {
return false;
}
return true;
}
bool delete_val;
T element;
int key;
bool default_node;
};
Hashtable() :
ht_keys(2), ht_size(0), dynamicArray(NULL) {
dynamicArray = new Node[ht_keys];
for (int i = 0; i < ht_keys; i++) {
dynamicArray[i].delete_val = false;
dynamicArray[i].key=0;
dynamicArray[i].default_node = false;
}
}
//seriously damaged programming...
Hashtable(Node* array, int HT_keys, int HT_size) :
ht_keys(HT_keys), ht_size(HT_size) {
dynamicArray = new Node[ht_keys];
if (array != NULL) {
for (int i = 0; i < ht_keys; i++) {
dynamicArray[i] = array[i];
}
}
}
Hashtable(const Hashtable& ht) {
if (&ht == this) {
return;
}
ht_keys = ht.ht_keys;
ht_size = ht.ht_size;
dynamicArray = new Node[ht_keys];
for (int i = 0; i < ht.ht_keys; i++) {
this->dynamicArray[i] = ht.dynamicArray[i];
}
}
~Hashtable() {
delete[] this->dynamicArray;
}
Hashtable operator=(const Hashtable& ht) {
Hashtable<T> newHT = ht;
return newHT;
}
//Returns true if some value equal to value exists within the hash table.
bool contains(Node n, int i) {
if (i < 0 || i > ht_keys || !n) {
return false;
}
if (i == ht_keys) {
return false;
}
//make sure that n.delete_val is not set as true.
if (dynamicArray[i]->element == n.element
&& !dynamicArray[i]->delete_val) {
return true;
}
if (dynamicArray[i]->delete_val) {
return contains(n, i + 1);
}
return false;
return true;
}
//Returns true if some key equal to key exists within the hash table.
bool containsKey(int i) {
if (i < 0 || i > ht_keys) {
return false;
}
if (dynamicArray[i]->element && !dynamicArray[i]->delete_val) {
return true;
}
return false;
}
//Returns true if some value equal to value exists within the hash table.
bool containsValue(T e) {
return true;
}
//Returns an enumeration of the values contained in the hash table.
int enumeration() {
return ht_size;
}
//Returns the object that contains the value associated with key.
//If key is not in the hash table, a null object is returned.
Node get(int i) {
if (i >= 0) {
return dynamicArray[i % ht_keys];
}
Node n;
return n;
}
//Returns true if the hash table is empty;
//returns false if it contains at least one key.
bool isEmpty() {
if (ht_size) {
return false;
}
return true;
}
//Returns an enumeration of the keys contained in the hash table.
int keys();
//Inserts a key and a value into the hash table.
//Returns false if key isn't already in the hash table;
//returns true if key is already in the hash table.
bool put(T e, int i) {
if (e && i > 0) {
Node n;
n.default_node = false;
n.delete_val = false;
n.key = i;
n.element = e;
//line 168
for (int j = (i % ht_keys); j < ht_keys; j = ((j + 1) % ht_keys)) { //line 169
if (!dynamicArray[j % ht_keys].element
|| dynamicArray[j % ht_keys].delete_val) {
dynamicArray[j % ht_keys] = n;
ht_size++;
return true;
}else if (i == (j + 1) % ht_keys) {
rehash();
return put(e, i);
}
}
return false;
}
return false;
}
bool put_aux(Node n, int i, Node* Array, int HT_keys) {
for (int j = (i % HT_keys); j < HT_keys; j = ((j + 1) % HT_keys)) {
if (!Array[j % HT_keys].element || Array[j % HT_keys].delete_val) {
Array[j % HT_keys] = n;
return true;
} else if (Array[j % HT_keys].element == n.element) {
return true;
}
}
return false;
}
//Increases the size of the hash table and rehashes all of its keys.
void rehash() {
int old_ht_keys = ht_keys;
ht_keys = DIV * ht_keys;
Node* newArray = new Node[ht_keys];
if (ht_keys > DIV) {
for (int j = 0; j < old_ht_keys; j++) {
put_aux(dynamicArray[j],dynamicArray[j].key,newArray,ht_keys);
}
}
delete[] dynamicArray;
dynamicArray = newArray;
}
//Removes key and its value.
//Returns the value associated with key.
//If key is not in the hash table, a null objecht_sizet is returned.
T remove(int i) {
if (i >= 0 && i < ht_keys) {
Node deleted_node(true, dynamicArray[i % ht_keys]);
dynamicArray[i % ht_keys] = deleted_node;
ht_size--;
return deleted_node.element;
}
return NULL;
}
//Returns the number of entries in the hash table.
int size() {
return this->ht_size;
}
private:
int ht_keys;
int ht_size;
Node* dynamicArray;
};
#endif /* HASH_TABLE_HPP_ */
It seems to be complaining about the line !dynamicArray[j % ht_keys].element (on line 163 of the code you posted; this would be a lot easier if the code you posted matched the code valgrind was using; right now the code you posted is several lines shorter than the code valgrind is using).
You never initialize the element member when you allocate the memory in the constructor. You then attempt to use it here in a conditional statement. valgrind correctly warns you of the problem.