Why the search and successor and predecessor returns -1?
// BST.cpp : main project file.
#include "stdafx.h"
#include <cstdlib>
#include <iostream>
#define SIZE 10
using namespace std;
struct Node {
int value;
Node *left;
Node *right;
Node *parent;
};
struct BST {
Node *root;
};
void insert(int value, BST *tree) {
Node *x = tree->root;
Node *y = NULL;
Node *z = (Node *) malloc(sizeof(Node));
z->left = NULL;
z->right = NULL;
z->value = value;
// Add your code here
while (x!=NULL){
y=x;
if (z->value < x->value)
x= x->left;
else x = x->right;
}
z->parent=y;
if (y==NULL)
tree->root=z;
else if (z->value <y->value)
y->left =z;
else y->right =z;
}
Node *search(int key, Node *n) {
if (n== NULL || key == n->value)
return n;
if (key < n->value)
search(key, n->left);
else
search(key, n->right);
}
Node *min(Node *n) {
if (n == NULL || n->left == NULL)
return n;
else
return min(n->left);
}
Node *max(Node *n) {
if (n == NULL || n->right == NULL)
return n;
else
return max(n->right);
}
Node *successor(int value, Node *n) {
Node *y = NULL;
Node *x = search(value, n);
if (x == NULL)
return NULL;
if (x->right != NULL)
return min(x->right);
y = x->parent;
while (y != NULL && x == y->right) {
x = y;
y = y->parent;
}
return y;
}
Node *predecessor(int value, Node *n) {
Node *x = search(value, n);
Node *y = NULL;
if (x == NULL)
return NULL;
if (x->left != NULL)
return max(x->left);
y = x->parent;
while (y != NULL && x == y->left) {
x = y;
y = y->parent;
}
return y;
}
Node *remove(int value, BST *tree) {
Node *z = search(value, tree->root);
Node *y = NULL, *x = NULL;
if (z == NULL) return NULL;
if (z->left == NULL || z->right == NULL)
y = z;
else
y = successor(value, z);
if (y->left != NULL)
x = y->left;
else
x = y->right;
if (x != NULL)
x->parent = y->parent;
if (y->parent == NULL)
tree->root = x;
else if (y == y->parent->left)
y->parent->left = x;
else
y->parent->right = x;
if (y != z) {
int tmp = z->value;
z->value = y->value;
y->value = tmp;
}
return y;
}
// ascending sort function
void sortAsc(Node *node) {
//Add your code here
//inorder
if (node->left!=NULL)
sortAsc(node->left);
cout<<node->value<<" ";
if (node->right!=NULL)
sortAsc(node->right);
}
// descending sort function
void sortDes(Node *node) {
// Add your code here
//inorder
if (node->right!=NULL)
sortDes(node->right);
cout<<node->value<<" ";
if (node->left!=NULL)
sortDes(node->left);
}
void clear(BST *tree) {
Node *n = NULL;
while (tree->root != NULL) {
n = remove(tree->root->value, tree);
free(n);
}
}
int main() {
int A[] = {3, 5, 10, 4, 8, 9, 1, 4, 7, 6};
Node *node = NULL;
BST *tree = (BST *) malloc(sizeof(BST));
tree->root = NULL;
// build BST tree
cout << "Input data:\n\t";
for (int i=0; i<SIZE; i++) {
cout << A[i] << " "; // by the way, print it to the console
insert(A[i], tree); // You need to complete TASK 1, so that it can work
}
// sort values in ascending order
cout << "\n\nAscending order:\n\t";
sortAsc(tree->root); // You need to complete TASK 2. Otherwise you see nothing in the console
// sort values in descending order
cout << "\n\nDescending order:\n\t";
sortDes(tree->root); // TASK 2 also!
// Find minimum value
if (tree->root != NULL)
cout << "\n\nMin: " << min(tree->root)->value;
// Find maximum value
if (tree->root != NULL)
cout << "\n\nMax: " << max(tree->root)->value;
// delete 4
cout << "\n\nDelete 4 and add 2";
//free(remove(4, tree)); // You need to complete TASK 3, so that remove(int, BST *) function works properly
// we also need to release the resource!!!
// insert 2
insert(2, tree); // It belongs to TASK 1 too.
cout << "\n\nAscending order:\n\t";
sortAsc(tree->root); // TASK 2!!
// Find the successor of 5, -1 means no successor
node = search(5, tree->root);
cout << "\n\nSearch of 5 is: " << (node != NULL?node->value:-1);
// Find the successor of 5, -1 means no successor
node = successor(5, tree->root);
cout << "\n\nSuccessor of 5 is: " << (node != NULL?node->value:-1);
// Find the predecessor of 5. -1 means no predecessor
node = predecessor(5, tree->root);
cout << "\n\nPredecessor of 5 is: " << (node != NULL?node->value:-1);
cout << "\n\n";
// clear all elements
clear(tree); // delete all nodes and release resource
free(tree); // delte the tree too
system("Pause");
}
Well there is a bug in your recursive search for starters you need to have all paths return values like this:
Node *search(int key, Node *n) {
if (n== NULL || key == n->value)
return n;
if (key < n->value)
return search(key, n->left);
else
return search(key, n->right);
}
Apart from that I'm inclined to say try debugging your own code first and giving more details about what you've found rather than just posting code and asking what's wrong with it. You're liable to get some real smart ass answers here otherwise ;)
Related
i tried building a binary search tree, everything worked fine when i gave it parameters that were in in the tree, but i wanted to see if it would print 0 when it couldn't find the int in the tree instead when i call search it's crashing.
i tried adding a condition after the first if statement but that ruined the recursion
here's the code:
struct node
{
int data;
node* left;
node* right;
node(int d)
{
data = d;
left = right = NULL;
}
};
node* insert(node *root, int n)
{
if(root == NULL)
{
return new node(n);
}
else
{
node* y;
if(n <= root->data)
{
y = insert(root->left, n);
root->left = y;
}
else
{
y = insert(root->right, n);
root->right = y;
}
return root;
}
}
node* search(node *root,int n)
{
if(root == NULL || root->data == n)
{
return root;
}
if(root->data < n)
{
return search(root->right, n);
}
return search(root->left, n);
}
int treemax(node *root)
{
while(root->right != NULL)
{
root = root->right;
}
return root->data;
}
int treemin(node *root)
{
while(root->left != NULL)
{
root = root->left;
}
return root->data;
}
int main()
{
node *R = NULL;
R = insert(R, 33);
insert(R,12);
insert(R, 40);
insert(R, 36);
insert(R, 21);
cout << search(R, 65)->data << endl;
}
Your problem is that you are trying to access null pointer. Pointer returned from search(R,65) is null because аt last step your root->right is null.
If you want to return 0 if no elements is found you can replace your last line with this:
node *result = search(R, 65);
if (result)
cout << result->data << endl;
else
cout << "0" << endl;
Below is a working example. I have added some comments that show what things you can change in the above program to make it safe or better.
#include<iostream>
struct node
{
//always initialize built-in type data members
int data = 0;//initialize any built in type otherwise it will have garbage value
node* left = nullptr;//initialize any built type as stated above
node* right = nullptr;//initialize any built in type as stated above
node(int d)
{
data = d;
left = right = nullptr;
}
};
node* insert(node *root, int n)
{
if(root == nullptr)
{
return new node(n);
}
else
{
node* y;
if(n <= root->data)
{
y = insert(root->left, n);
root->left = y;
}
else
{
y = insert(root->right, n);
root->right = y;
}
return root;
}
}
node* search(node *root,int n)
{
if(root == nullptr || root->data == n)
{
return root;
}
if(root->data < n)
{
return search(root->right, n);
}
return search(root->left, n);
}
int treemax(node *root)
{
while(root->right != nullptr)
{
root = root->right;
}
return root->data;
}
int treemin(node *root)
{
while(root->left != nullptr)
{
root = root->left;
}
return root->data;
}
int main()
{
node *R = nullptr;
R = insert(R, 33);
insert(R,12);
insert(R, 40);
insert(R, 36);
insert(R, 21);
//std::cout << search(R, 65)->data << std::endl;
node *value = search(R, 65);
//check if the pointer is valid
if(value)
{
std::cout<< value->data <<std::endl;
}
else
{
std::cout<<"cannot access nullptr"<<std::endl;
}
}
The error was because search(R, 65); was returning NULL and you were trying to access a NULL pointer's data member value.
When you run
cout << search(R, 65)->data << endl;
search(R, 65) returns NULL. You can't dereference NULL by doing ->data on it. You probably want:
Node* result = search(R, 65);
if (result)
{
cout << result->data << endl;
}
else
{
cout << "Not found" << endl;
}
I have an AVL tree program that sorts a text file, stored as a string, using in-order traversal. This works as intended and is shown below
std::string fileName;
std::fstream readFile;
std::string storeFile;
struct Node
{
std::string key;
int height;
Node *left;
Node *right;
};
int max(int a, int b);
int height(Node *N)
{
if (N == NULL)
return 0;
return N->height;
}
int max(int lower, int upper)
{
return (lower > upper) ? lower : upper;
}
Node *newNode(std::string key)
{
Node *node = new Node();
node->key = key;
node->left = NULL;
node->right = NULL;
node->height = 1;
return node;
}
Node *rightRotation(Node *y)
{
Node *x = y->left;
Node *z = x->right;
x->right = y;
y->left = z;
y->height = max(height(y->left), height(y->right)) + 1;
x->height = max(height(x->left), height(x->right)) + 1;
return x;
}
Node *leftRotation(Node *x)
{
Node *y = x->right;
Node *z = y->left;
y->left = x;
x->right = z;
x->height = max(height(x->left), height(x->right)) + 1;
y->height = max(height(y->left), height(y->right)) + 1;
return y;
}
// Get Balance factor of node N
int getBalance(Node *N)
{
if (N == NULL)
return 0;
return height(N->left) - height(N->right);
}
Node *insertnewNode(Node *node, std::string key)
{
if (node == NULL)
return (newNode(key));
if (key < node->key)
node->left = insertnewNode(node->left, key);
else if (key > node->key)
node->right = insertnewNode(node->right, key);
else
return node;
node->height = 1 + max(height(node->left),
height(node->right));
int balance = getBalance(node);
if (balance > 1 && key < node->left->key)
return rightRotation(node);
if (balance < -1 && key > node->right->key)
return leftRotation(node);
if (balance > 1 && key > node->left->key)
{
node->left = leftRotation(node->left);
return rightRotation(node);
}
if (balance < -1 && key < node->right->key)
{
node->right = rightRotation(node->right);
return leftRotation(node);
}
return node;
}
void Inorder(Node *root)
{
if (root == NULL)
return;
Inorder(root->left); //visit left sub-tree
std::cout << root->key << std::endl; //visit root(key node)
Inorder(root->right); //visit right sub-tree
}
bool wordCount(const Node &node1, const Node &node2)
{
}
int main(int argc, char *argv[])
{
Node *root = NULL; //pointer to bstNode. Store address of root node.
//set to NULL(empty tree)
std::cout << "Please enter the name of the file: " << std::endl; //prompts user for the filename
std::cin >> argv[0]; //stores the filename is the first element of argv[]
fileName = argv[0];
std::cout << "Attempting to read file " << fileName << std::endl;
readFile.open(fileName); //attempts to read the file
if (!readFile)
{
std::cerr << "ERROR: failed to open file " << std::endl; //if the file cannot be opened an error is displayed
exit(0); //if it cannot open the console terminates
}
else
{
std::cerr << "File successfully opened" << std::endl;
}
while (readFile >> storeFile)
{
std::transform(storeFile.begin(), storeFile.end(), storeFile.begin(), ::tolower);
for (int i = 0, len = storeFile.size(); i < len; i++)
{
// check whether parsing character is punctuation or not
if (ispunct(storeFile[i]))
{
storeFile.erase(std::remove_if(storeFile.begin(), storeFile.end(), ::isspace), storeFile.end());
storeFile.erase(std::remove_if(storeFile.begin(), storeFile.end(), ::ispunct), storeFile.end());
}
}
root = insertnewNode(root, storeFile);
}
Inorder(root);
readFile.close();
return 0;
}
The implementation im currently struggling with is the count of each word. So for exmaple below, the word is on the left and the count is on the right
adams: 2
apple: 5
as: 20
I attempted a function called bool countWords which the paramaters I believe would be needed(in this case two nodes to compare and match a case). However im not to sure myself how to implemenent it
Thankyou
Just because this hasn't been answered yet, here's the idea behind the solution which I've proposed. You have already converted the input from the file to lowercase, so we can assume that all of the strings are the same case:
typedef std::map<std::string, uint32_t> omap;
omap occurrences;
void printNumOccur( const omap& m )
{
for ( omap::it = m.begin(); it != m.end(); ++it )
{
std::cout << it->first << ": " << it->second << std::endl;
}
}
Node *insertnewNode(Node *node, std::string key)
{
if (node == NULL)
return (newNode(key));
omap::iterator it;
if ( (it = occurrences.find(key)) != m.end() )
it->second++;
else
occurrences.insert({key, 1});
if (key < node->key)
node->left = insertnewNode(node->left, key);
else if (key > node->key)
node->right = insertnewNode(node->right, key);
else
return node;
node->height = 1 + max(height(node->left),
height(node->right));
int balance = getBalance(node);
if (balance > 1 && key < node->left->key)
return rightRotation(node);
if (balance < -1 && key > node->right->key)
return leftRotation(node);
if (balance > 1 && key > node->left->key)
{
node->left = leftRotation(node->left);
return rightRotation(node);
}
if (balance < -1 && key < node->right->key)
{
node->right = rightRotation(node->right);
return leftRotation(node);
}
return node;
}
It seems like the easiest approach would be to maintain the count of each string in the node and increment it every time a matching node is found.
struct Node
{
std::string key;
int height;
Node *left;
Node *right;
int count;
};
Node* newNode(std::string const& key)
{
Node *node = new Node();
node->key = key;
node->left = NULL;
node->right = NULL;
node->height = 1;
node->count = 1;
return node;
}
if (key < node->key)
node->left = insertnewNode(node->left, key);
else if (key > node->key)
node->right = insertnewNode(node->right, key);
else
{
node->count++;
return node;
}
Once the tree is assembled you will need to iterate all nodes. There are two ways you could do this:
Whenever creating a new node, add a pointer to it in a vector
Write a "TreeBrowser" class to scan the tree and dump the outputs. If you want the output to be in order, you will need to walk up and down the tree, remembering what level each branch started from.
Consider the following AVL-tree implementation. Each node contains a list of numbers.The key is named workload, but consider it as a plain double variable. If a key is equal to the key of an already existing node, the number gets pushed into the list. Every time I pop a number from a list, I perform a check, if the node's list is empty -> remove the node. But, after the element with key=3 gets removed completely, the list of the node with key=4 is suddenly empty. I've been trying to solve it for over 10 hours now, it's actually the first time I ever needed to ask something here. Pardon me if I miss a few things.
#include<iostream>
#include <list>
using namespace std;
class BST
{
struct node
{
double workload;
list<int> numbers;
node* left;
node* right;
int height;
};
node* root;
unsigned long long size;
bool empty;
void makeEmpty(node* t)
{
if(t == NULL)
return;
makeEmpty(t->left);
makeEmpty(t->right);
delete t;
}
node* insert(double workload,int number, node* t)
{
if(t == NULL)
{
t = new node;
t->workload = workload;
t->numbers.push_back(number);
t->height = 0;
t->left = t->right = NULL;
}
else if(t->workload == workload){
t->numbers.push_back(number);
}
else if(workload < t->workload)
{
t->left = insert(workload, number, t->left);
if(height(t->left) - height(t->right) == 2)
{
if(workload < t->left->workload)
t = singleRightRotate(t);
else
t = doubleRightRotate(t);
}
}
else if(workload > t->workload)
{
t->right = insert(workload, number, t->right);
if(height(t->right) - height(t->left) == 2)
{
if(workload > t->right->workload)
t = singleLeftRotate(t);
else
t = doubleLeftRotate(t);
}
}
//if x == t->workload instead of using int workload. its a list and we push into it.
t->height = max(height(t->left), height(t->right))+1;
return t;
}
node* singleRightRotate(node* &t)
{
node* u = t->left;
t->left = u->right;
u->right = t;
t->height = max(height(t->left), height(t->right))+1;
u->height = max(height(u->left), t->height)+1;
return u;
}
node* singleLeftRotate(node* &t)
{
node* u = t->right;
t->right = u->left;
u->left = t;
t->height = max(height(t->left), height(t->right))+1;
u->height = max(height(t->right), t->height)+1 ;
return u;
}
node* doubleLeftRotate(node* &t)
{
t->right = singleRightRotate(t->right);
return singleLeftRotate(t);
}
node* doubleRightRotate(node* &t)
{
t->left = singleLeftRotate(t->left);
return singleRightRotate(t);
}
node* findMin(node* t)
{
if(t == NULL)
return NULL;
else if(t->left == NULL)
return t;
else
return findMin(t->left);
}
node* findMax(node* t)
{
if(t == NULL)
return NULL;
else if(t->right == NULL)
return t;
else
return findMax(t->right);
}
node* find(node* t,double workload){
if (t->workload == workload){
return t;
}
else if(workload < t->workload && t->left!=NULL)
return find(t->left,workload);
else if(workload > t->workload && t->right!=NULL)
return find(t->right,workload);
else{
cout << "Null node encountered" << endl;
return t;
}
}
node* remove(double x, node* t)
{
node* temp;
// Element not found
if(t == NULL)
return NULL;
// Searching for element
if(x < t->workload)
t->left = remove(x, t->left);
else if(x > t->workload)
t->right = remove(x, t->right);
// Element found
// With 2 children
else if(t->left && t->right)
{
temp = findMin(t->right);
t->workload = temp->workload;
t->right = remove(t->workload, t->right);
}
// With one or zero child
else
{
temp = t;
if(t->left == NULL)
t = t->right;
else if(t->right == NULL)
t = t->left;
delete temp;
}
if(t == NULL)
return t;
t->height = max(height(t->left), height(t->right))+1;
// If node is unbalanced
// If left node is deleted, right case
if(height(t->left) - height(t->right) == -2)
{
// right right case
if(height(t->right->right) - height(t->right->left) == 1)
return singleLeftRotate(t);
// right left case
else
return doubleLeftRotate(t);
}
// If right node is deleted, left case
else if(height(t->right) - height(t->left) == 2)
{
// left left case
if(height(t->left->left) - height(t->left->right) == 1){
return singleRightRotate(t);
}
// left right case
else
return doubleRightRotate(t);
}
return t;
}
int height(node* t)
{
return (t == NULL ? -1 : t->height);
}
int getBalance(node* t)
{
if(t == NULL)
return 0;
else
return height(t->left) - height(t->right);
}
void inorder(node* t)
{
if(t == NULL)
return;
inorder(t->left);
cout << t->workload<< " ";
inorder(t->right);
}
//Reverse inorder (Sorted highest to lowest)
void rinorder(node* t)
{
if(t == NULL)
return;
rinorder(t->right);
cout << t->workload << " ";
rinorder(t->left);
}
void preorder(node* t)
{
if (t == NULL)
return;
cout << t->workload << " ";
preorder(t->left);
preorder(t->right);
}
void postorder(node* t)
{
if (t == NULL)
return;
postorder(t->left);
postorder(t->right);
cout << t->workload << " ";
}
public:
BST()
{
root = NULL;
}
void insert(double workload, int number)
{
root = insert(workload, number, root);
}
void remove(double workload)
{
root = remove(workload, root);
}
void displayrin()
{
cout << "Rinorder: ";
rinorder(root);
cout << endl;
}
void displayin()
{
cout << "Inorder: ";
inorder(root);
cout << endl;
}
void displaypost()
{
cout << "Postorder: ";
postorder(root);
cout << endl;
}
void displaypre()
{
cout << "Preorder: ";
preorder(root);
cout << endl;
}
double getMax(){
return findMax(root)->workload;
}
int getMaxNum(){
return find(root,getMax())->numbers.front();
}
int getNum(double workload){
return find(root,workload)->numbers.front();
}
//We pop a Num from a node
void popnumber(double workload){
node *t = find(root,workload);
if(t!=NULL){
if(!t->numbers.empty()){
t->numbers.pop_front();
//If the Num list of the node is empty, remove node
if(t->numbers.empty()){
remove(t->workload);
}
}
}
}
};
int main()
{
BST t;
//key value pairs
t.insert(2,1);
t.insert(3,1);
t.insert(3,2);
t.insert(4,7);
cout << t.getNum(4) << endl;
cout << t.getNum(3)<<endl;
t.popnumber(3);
cout << t.getNum(3)<<endl;
t.popnumber(3);
t.displayin();
t.displaypost();
t.displaypre();
t.displayrin();
cout << t.getNum(4) << endl;
cout << "The max is : " << t.getMax() << endl;
cout << "The top Num of the Max is : " << t.getMaxNum() << endl;
return 0;
}
As mentioned in the comments, the problem is in the "Element found With 2 children" section of remove.
To remove the element, you find the next element in the tree. Your implementation then wants to copy the contents of the found node (temp). You copy the workload value, so that both t and temp have the same workload value (4). You do not copy the numbers list. The t node has a workload of 4 and an empty numbers list, while temp has a workload of 4 and a numbers list consisting of one element, 7. You then delete temp, losing the list.
One fix would be to copy (or move) numbers from temp to t before removing it from the tree. Adding a MoveData method to node that would move the data fields (while not altering the tree specific fields) would make it easier to add new data fields.
Another fix would be to change how you're doing the data update. If you update all pointers (and other tree related fields like height), then you don't have to worry about the data (and any pointers/iterators to the nodes would not be invalidated).
I have a problem with my C++ code. It says that the all the functions starting with isPerfectRec() couldn't be resolved...Why? I tried a lot of things but apparently they don't work. I have a lot of assigments like to verify if the binary search tree is perfect, to find the second largest element in a binary search tree and so on..
#include <stdio.h>
#include<iostream>
#include<stack>
template<typename T> class BinarySearchTree {
public:
BinarySearchTree<T> *root, *left_son, *right_son, *parent;
T *pinfo;
BinarySearchTree() {
left_son = right_son = NULL;
root = this;
pinfo = NULL;
}
void setInfo(T info) {
pinfo = new T;
*pinfo = info;
}
void insert(T x) {
if (pinfo == NULL)
setInfo(x);
else
insert_rec(x);
}
bool isPerfectRec(BinarySearchTree *root, int d, int level = 0)
{
// An empty tree is perfect
if (*root == NULL)
return true;
// If leaf node, then its depth must be same as
// depth of all other leaves.
if (*root->left_son == NULL && root->*right_son == NULL)
return (d == level+1);
// If internal node and one child is empty
if (root->*left_son == NULL || root->*right_son == NULL)
return false;
// Left and right subtrees must be perfect.
return isPerfectRec(root->*left_son, d, level+1) &&
isPerfectRec(root->*right_son, d, level+1);
}
// Wrapper over isPerfectRec()
bool isPerfect(BinarySearchTree *root)
{
int d = findADepth(root);
return isPerfectRec(root, d);
}
int findADepth(BinarySearchTree *node)
{
int d = 0;
while (node != NULL)
{
d++;
node = node->left_son;
}
return d;
}
// A function to find 2nd largest element in a given tree.
void secondLargestUtil(BinarySearchTree *root, int &c)
{
// Base cases, the second condition is important to
// avoid unnecessary recursive calls
if (root == NULL || c >= 2)
return;
// Follow reverse inorder traversal so that the
// largest element is visited first
secondLargestUtil(root->right_son, c);
// Increment count of visited nodes
c++;
// If c becomes k now, then this is the 2nd largest
if (c == 2)
{
std::cout << "2nd largest element is "
<< root->pinfo;
printf("\n___\n");
return;
}
// Recur for left subtree
secondLargestUtil(root->left_son, c);
}
void secondLargest(BinarySearchTree *root)
{
// Initialize count of nodes visited as 0
int c = 0;
// Note that c is passed by reference
secondLargestUtil(root, c);
}
bool hasOnlyOneChild(int pre[], int size)
{
int nextDiff, lastDiff;
for (int i=0; i<size-1; i++)
{
nextDiff = pre[i] - pre[i+1];
lastDiff = pre[i] - pre[size-1];
if (nextDiff*lastDiff < 0)
return false;;
}
return true;
}
BinarySearchTree * readListInter(){
BinarySearchTree* root = NULL;//returning object
BinarySearchTree* temp;
BinarySearchTree* input;//new node to add
int x;
std::cout << "enter number (>0 to stop): ";
std::cin >> x;
while(x>=0){
input = BinarySearchTree(x);
if(root == NULL){//if root is empty
root = input;
temp = root;//temp is use to store value for compare
}
else{
temp = root; //for each new addition, must start at root to find correct spot
while(input != NULL){
if( x < temp->pinfo){//if smaller x to add to left
if(temp->left_son == NULL){//left is empty
temp->left_son = input;
input = NULL;//new node added, exit the loop
}
else{//if not empty set temp to subtree
temp = temp->left_son;//need to move left from the current position
}
}
else{//otherwise x add to right
if(temp->right_son == NULL){//right is empty
temp->right_son = input;
input = NULL;//new node added, exit the loop
}
else{
temp = temp->right_son;//need to move right from the current position
}
}
}
}
std::cin >> x;
}
return root;
}
};
int main() {
BinarySearchTree<int> *r = new BinarySearchTree<int>;
BinarySearchTree<int> *r1 = new BinarySearchTree<int>;
BinarySearchTree<int> *p = new BinarySearchTree<int>;
p = readListInter();
r->insert(6);
r->insert(8);
r->insert(1);
r->insert(9);
r->insert(10);
r->insert(4);
r->insert(13);
r->insert(12);
printf("\n___\n");
r1->insert(6);
r1->insert(8);
r1->insert(1);
r1->insert(9);
r1->insert(10);
r1->insert(4);
r1->insert(13);
r1->insert(12);
printf("\n___\n");
r->isPerfect(r);
int pre[] = {8, 3, 5, 7, 6};
int size = sizeof(pre)/sizeof(pre[0]);
if (hasOnlyOneChild(pre, size) == true )
printf("Yes");
else
printf("No");
s
return 0;
}
I think you need to write BinarySearchTree<T> instead of BinarySearchTree as a datatype in those functions.
The following code calculates the sum of the elements of the unidirectional list items greater than 3 and smaller than 8 and the result of the sum is changed the beginning of the list.
#include <iostream>
using namespace std;
struct List
{
int num;
List* nItem;
};
int Input()
{
int number;
cout << "Enter the number: "; cin >> number;
return number;
}
void MakeList(List **head, int n)
{
if (n > 0) {
*head = new List;
(*head)->num = Input();
(*head)->nItem = NULL;
MakeList(&(*head)->nItem, n - 1);
}
}
void Print(List* head)
{
if (head != NULL) {
cout << head->num << " ";
Print(head->nItem);
}
}
List* Add_start(List* head, int index, int elm)
{
List* p = new List;
p->num = elm;
p->nItem = NULL;
if (head == NULL) {
head = p;
}
else {
List* current = head;
for (int i = 0; (i < index - 1) && (current->nItem != NULL); i++)
{
current = current->nItem;
}
if (index == 0)
{
p->nItem = head;
head = p;
}
else {
if (current->nItem != NULL) {
p->nItem = current->nItem;
}
current->nItem = p;
}
}
return head;
}
int Sum(List* head)
{
int sum = 0;
List* p = head;
while(p) {
if ((p->num > 3) && (p->num < 8))
sum += p->num;
p = p->nItem;
}
return sum;
}
void DeleteList(List* head)
{
if (head != NULL) {
DeleteList(head->nItem);
delete head;
}
}
int main()
{
int n = 10;
List* head = NULL;
cout << "Enter 10 number to the list\n" << endl;
MakeList(&head, n);
int sum = Sum(head);
head = Add_start(head, 0, sum);
cout << "\nList: ";
Print(head);
cout << endl;
DeleteList(head);
system("pause");
return 0;
}
How can I do the same operation with a bidirectional list?
Notes:
A bidirectional (or double linked) list, also has a member pointing to the previous node: this is the whole difference between the 2 list types (as a consequence the first element - or the one at the left of the list, will have this member pointing to NULL). So, when such a node is created/inserted into a list, this new member should be set as well (I commented in the code places where this happens), for the new node and for the one following it (if any).
I modified the way of how a list is created - MakeList replaced by _MakeList2 + MakeList2; the underscore(_) in _MakeList2 specifies that it's somehow private (convention borrowed from Python) - it's not very nice, but I thought it's easier this way
I don't have Visual Studio on this computer, so I used gcc. It complained about system function so I had to add #include <stdlib.h>
I renamed some of the identifiers (List -> Node, Add_start -> AddNode, nItem -> nNode) either because the new names make more sense, or their names are consistent
I tried to keep the changes to a minimum (so the solution is as close as possible to your original post)
I enhanced (by adding an additional argument: toRight (default value: 1)) the Print func, so it can iterate the list both ways - I am iterating right to left (for testing purposes) before deleting the list
I corrected some (minor) coding style issues
Here's the modified code:
#include <iostream>
#include <stdlib.h>
using namespace std;
struct Node {
int num;
Node *pNode, *nNode; // Add a new pointer to the previous node.
};
int Input() {
int number;
cout << "Enter the number: "; cin >> number;
return number;
}
Node *_MakeList2(int n, Node *last=NULL) {
if (n > 0) {
Node *node = new Node;
node->num = Input();
node->pNode = last;
node->nNode = _MakeList2(n - 1, node);
return node;
}
return NULL;
}
Node *MakeList2(int n) {
return _MakeList2(n);
}
void Print(Node *head, int toRight=1) {
if (head != NULL) {
cout << head->num << " ";
if (toRight)
Print(head->nNode, 1);
else
Print(head->pNode, 0);
}
}
Node* AddNode(Node *head, int index, int elm) {
Node *p = new Node;
p->num = elm;
p->pNode = NULL; // Make the link between this node and the previous one.
p->nNode = NULL;
if (head == NULL) {
head = p;
} else {
Node *current = head;
for (int i = 0; (i < index - 1) && (current->nNode != NULL); i++) {
current = current->nNode;
}
if (index == 0) {
p->nNode = head;
head->pNode = p; // Make link between next node's previous node and the current one.
head = p;
} else {
if (current->nNode != NULL) {
p->nNode = current->nNode;
}
p->pNode = current; // Make the link between this node and the previous one.
current->nNode = p;
}
}
return head;
}
int Sum(Node* head) {
int sum = 0;
Node *p = head;
while(p) {
if ((p->num > 3) && (p->num < 8))
sum += p->num;
p = p->nNode;
}
return sum;
}
void DeleteList(Node *head) {
if (head != NULL) {
DeleteList(head->nNode);
delete head;
}
}
int main() {
int n = 10;
Node *head = NULL, *tail = NULL;
cout << "Enter " << n << " number(s) to the list" << endl << endl;
head = MakeList2(n);
int sum = Sum(head);
head = AddNode(head, 0, sum);
cout << endl << "List: ";
Print(head);
cout << endl;
tail = head;
if (tail) {
while (tail->nNode != NULL)
tail = tail->nNode;
cout << endl << "List reversed: ";
Print(tail, 0);
cout << endl;
}
DeleteList(head);
system("pause");
return 0;
}