Binary Search Tree does not add to the right of the root - c++

I am writing a templated binary search tree class, the function I use to create the binary search tree is the following:
void insert(const Comparable & x, BinaryNode<Comparable> * & t)
{
if (t==NULL)
t = new BinaryNode<Comparable>(x, NULL, NULL);
else if (x < t->element)
insert(x, t->left);
else if (x>t->element)
insert(x, t->right);
else
; // Duplicate;
}
and BinaryNode is another templated class as the following:
template <class Comparable>
class BinaryNode
{
public:
Comparable element;
BinaryNode *left;
BinaryNode *right;
BinaryNode(const Comparable & theElement,
BinaryNode *lt, BinaryNode *rt)
: element(theElement), left(lt), right(rt) { }
};
The problem is, whenever I create a new tree, it adds the first element as the root. Then even if the next element I want to add is greater than the root it adds to the left of the root. For the elements on the left of the tree, this problem does not occur, it propoerly adds it to the right whenever necessary. Can you help?
EDIT: Problem solved. I was reading a file line by line and storing those lines into nodes, it turned out that the getline gets the first line of the file in a way that it starts with weird characters-even though there exists none. Those characters always had a greater value from other normal letters, thus it always goes to the left of the tree.

Related

Recursive tree symmetry

I have written the following code snippet to determine if a Binary Tree is symmetrical or not:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool symmetricityChecker(TreeNode* root, int level) {
bool isValid=false;
if(root==NULL)
return true;
if(level==1)
isValid = root->left->val==root->right->val;
if(root->left!=NULL && root->right!=NULL) {
if(root->left->left!=NULL && root->right->right!=NULL)
isValid = root->left->left->val==root->right->right->val;
if(root->left->right!=NULL && root->right->left!=NULL)
isValid = root->left->right->val==root->right->left->val;
}
return isValid && symmetricityChecker(root->left, level+1) && symmetricityChecker(root->right, level+1);
}
bool isSymmetric(TreeNode* root) {
return symmetricityChecker(root, 0);
}
};
My aim is, at level 1, I check if the root's left and right children are equal (since at this level there is just a root and its two children). For all the remaining levels, I check if the left child of the root's left child is equal to the right child of the root's right child. Similarly, I check if the right child of the root's left child is equal to the left child of the root's right child. (This is so, because the symmetry of the root's immediate left and right children has already been checked in the previous recursive call).
I believe that my algorithm is correct, but it is generating incorrect results. Could someone kindly point out if my logic is incorrect, or are there errors in the implementation?
Edit: I tested the code for the input [1,2,2,3,4,4,3]. I expect the answer to be true, but get a false instead. Hence I am not sure if I have a logical flaw in my approach.
The wrong part is where you're doing that:
return isValid && symmetricityChecker(root->left, level+1) && symmetricityChecker(root->right, level+1);
By calling symmetricityChecker on a single child node, you're expecting the children to be symmetric as well, but this shouldn't be true. So it'll fail because the subtree [2,3,4] is not symmetric and consider the whole tree as not symmetric even if this is not true.
To check symmetry recursively, you have to keep two nodes (i.e. left and right) as your state, not just one. Once you confirm that the two nodes are symmetric, recursively check their children by a similar check to what you're doing above in the nested if conditions.
Another approach is to write a BFS, and check that all the nodes in the same level are symmetric. This way, it should be as easy as checking if an array is symmetric because you'll have all the nodes of the same level in the same array next to each other.
EDIT:
Adding a pseudocode:
bool symmetricityChecker(left, right) {
// Write the base case, check for nulls, corner cases, etc.
if(left != right) return false
return symmetricityChecker(left.left, right.right) &&
symmetricityChecker(left.right, right.left)
}
At the beginning when you only have the root, call this method with the root's children.

Deletion in bst tree

I have a binary search class and i want to write a function for deleting a special node but i don't know how.
the basic class is :
class Node {
friend class Tree;
private:
long long rep;
Node *left, *right;
string data;
public:
Node( string d )
: data( d ), left( NULL ), right( NULL ), rep( 1 ) {}
};
class Tree {
private:
Node *root;
public:
void delete_node( Node *cur , string s );
void delete_node_helper( string s );
};
There're 3 parts in deletion of a node from the binary search tree:
Find a node to delete.
Delete a node (free memory, etc).
Merge children of the deleted node.
In your particular code example, I'd say that looking for the node should be the responsibility of void delete_node_helper(string s);, deleting a node should be the responsibility of void delete_node(Node *cur, string s);, and merging the children should be the responsibility of the newly created function.
Given that the algorithms of the first two parts are pretty straighforward, let me explain in detail only the third one.
To merge two BSTs (of which we know which one is left and which one is right) we should decide who will be whose child and perform the recursive merging if necessary. The code looks like this:
Node* merge(Node* left, Node* right) {
if (left == nullptr) {
return right;
}
if (right == nullptr) {
return left;
}
if (rand() & 1) { // <- chose parent
left->right = merge(left->right, right);
return left;
}
right->left = merge(left, right->left);
return right;
}
On the marked line we actually make a decision on which node will be whose parent. In this particular example, the result is random, but any other strategy may be implemented. For example, you could store heights (or sizes) in all nodes of your tree and make the smaller tree root child of a larger tree root.
Delete a special node from a BST tree
I just tried the deletion code in above link and it worked nice.

Binary tree rotate function without reference-to-pointer, pointer-to-pointer, or the function returning the new node

I have to make an implementation of the following class in C++:
struct Node {
Node* parent;
Node* left;
Node* right;
std::string name;
};
class BinaryTree {
public:
BinaryTree();
std::string ToString() const;
void RotateLeft(Node* node);
void RotateRight(Node* node);
void MakePerfect();
private:
void CreateVine();
void MakePerfectFromVine();
private:
Node *root;
};
This class implements the DSW algorithm for making a Binary tree perfect (all levels are full, except the last one)
I have done an implementation which works, I tested it and everything seem fine but I had to change the rotate functions thus:
void RotateLeft(Node*& node);
void RotateRight(Node*& node);
Unfortunately the person who set me this task said that I'm forbidden to change them. But the unaltered functions don't work. I use them in CreateVine() and MakePerfectFromVine():
void CreateVine() {
Node *current = root;
while(current != NULL)
if(current->left != NULL){
current=current->left;
rotateRight(current);
}
else
current = current->right;
}
In this fragment the pointer current points to a node in the tree. After the node is rotated, it will have changed its parent and/or left and/or right child, but current will point to the old node with the old information. In order for the changes made in the rotate function to be reflected outside of the rotate function, I have to use reference-to-pointer, pointer-to-pointer or the function itself has to return the node;
The only way I can think of to fix this problem is if I know that the binary tree doesn't allow duplicate elements, after I rotate the node I search for its string value and set current to point to it, but I'm not sure if the binary tree doesn't allow duplicate elements and that would increase the time complexity of the algorithm.
Is there any way of avoiding the use of reference-to-pointer and pointer-to-pointer?
Excluding the root of the tree, for which you might have to think something else, the pointer to a given node inside the tree can be obtained with an extra level of indirection:
Node **pp;
if (node->parent->left == node)
pp = &node->parent->left;
else
pp = &node->parent->right;
So you can actually maintain your algorithm and just resolve the reference doing this inside the function. Note that this is a sketch, you will have to check for the root (parent==0) and operate differently there

Use Binary-Tree in Template as Priority queue

So i want to make a code, that creates a binary tree, that holds data, for example ints like 1,6,2,10,8 and on pop i get the biggest number, and after that it gets deleted from the tree, and on push i can insert a new element. And this should be in a template so i can easy change the data type i want to hold in the tree. Now i got the tree so far, without template it is working fine thought, i can add items, and i can print them, but when i try to put it in a template, i get the following error: use of class template requires template argument list . What could be the problem? Maybe i am doing it totally wrong. Any suggestions are welcome.
This was my first question it got fixed by avakar ty. (i will post the code at the end of my question)
I just read trough the project request , and its like, i have to make this thing i above in the first part of question described, but its like the binary tree should represent a priority queue. And that is why in the request is written that i have to use push to put a new element in the tree by priority order and with pop i will get the element with the highest priority and then that element will be deleted. So how could i use my Tree as a Priority queue, or is he already one(i think not but who knew)? I hope i could explain it.
And here is the code as promised:
#include <iostream>
using namespace std;
template<class T>
class BinaryTree
{
struct Node
{
T data;
Node* lChildptr;
Node* rChildptr;
Node(T dataNew)
{
data = dataNew;
lChildptr = NULL;
rChildptr = NULL;
}
};
private:
Node* root;
void Insert(T newData, Node* &theRoot)
{
if(theRoot == NULL)
{
theRoot = new Node(newData);
return;
}
if(newData < theRoot->data)
Insert(newData, theRoot->lChildptr);
else
Insert(newData, theRoot->rChildptr);;
}
void PrintTree(Node* theRoot)
{
if(theRoot != NULL)
{
PrintTree(theRoot->lChildptr);
cout<< theRoot->data<<" ";;
PrintTree(theRoot->rChildptr);
}
}
public:
BinaryTree()
{
root = NULL;
}
void AddItem(T newData)
{
Insert(newData, root);
}
void PrintTree()
{
PrintTree(root);
}
};
int main()
{
BinaryTree<int> *myBT = new BinaryTree<int>();
myBT->AddItem(1);
myBT->AddItem(7);
myBT->AddItem(1);
myBT->AddItem(10);
myBT->AddItem(4);
myBT->PrintTree();
}
If you want to use the binary tree as a priority queue, you extract the maximum element by stepping only through right child pointers. Any left child would be smaller than the current element. So you record the value of that node and then remove it -- you would still have to write a node deletion routine.
The problem with a simple BST is that it can become unbalanced and send your complexities to O(n). You can use a self-balancing BST, but it's unusual for priority queues. Instead of BSTs they are usually heaps, as Kerrek said.
The simplest heap implementation that I know personally is the binary heap. The binary heap is theoretically a type of binary tree although not stored as such. So, depending on whether you had to implement a BST or just a binary tree, it might fit your requirements.
On this line:
BinaryTree<int> *myBT = new BinaryTree();
You need to also specify the type of template you want to instantiate on the right side of the assignment:
BinaryTree<int> *myBT = new BinaryTree<int>();
Because BinaryTree is not a BinaryTree<int>; one is the name of a template (BinaryTree) and one is the name of a specific type of that template (BinaryTree<int>). You can't create instances of plain templates, you have to give it the type of template you want to use all the time.

How to structure this tree of nodes?

I'm writing a program in C++ that uses genetic techniques to optimize an expression tree.
I'm trying to write a class Tree which has as a data member Node root. The node constructor generates a random tree of nodes with +,-,*,/ as nodes and the integers as leaves.
I've been working on this awhile, and I'm not yet clear on the best structure. Because I need to access any node in the tree in order to mutate or crossbreed the tree, I need to keep a dicionary of the Nodes. An array would do, but it seems that vector is the recommended container.
vector<Node> dict;
So the Tree class would contain a vector dict with all the nodes of the tree (or pointers to same), the root node of the tree, and a variable to hold a fitness measure for the tree.
class Tree
{
public:
typedef vector<Node>dict;
dict v;
Node *root;
float fitness;
Tree(void);
~Tree();
};
class Node
{
public:
char *cargo;
Node *parent;
Node *left;
Node *right;
bool entry;
dict v;
Node(bool entry, int a_depth, dict v, Node *pparent = 0);
};
Tree::Tree()
{
Node root(true, tree_depth, v);
};
There seems to be no good place to put typedef vector<Node>dict;, because if it goes in the definition of Tree, it doesn't know about Node, and will give an error saying so. I havn't been able to find a place to typedef it.
But I'm not even sure if a vector is the best container. The Nodes just need to be indexed sequentally. The container would need to grow as there could be 200 to 500 Nodes.
I think a standard Binary Tree should do... here is an example of a (binary) expression tree node:
const int NUMBER = 0, // Values representing two kinds of nodes.
OPERATOR = 1;
struct ExpNode { // A node in an expression tree.
int kind; // Which type of node is this?
// (Value is NUMBER or OPERATOR.)
double number; // The value in a node of type NUMBER.
char op; // The operator in a node of type OPERATOR.
ExpNode *left; // Pointers to subtrees,
ExpNode *right; // in a node of type OPERATOR.
ExpNode( double val ) {
// Constructor for making a node of type NUMBER.
kind = NUMBER;
number = val;
}
ExpNode( char op, ExpNode *left, ExpNode *right ) {
// Constructor for making a node of type OPERATOR.
kind = OPERATOR;
this->op = op;
this->left = left;
this->right = right;
}
}; // end ExpNode
So when you're doing crossover or mutation and you want to select a random node you just do the following:
Count the number of nodes in the tree (only need to do this ones in the constructor).
Select a random index from 0 to the size of the tree.
Visit each node and subtract 1 from the random index until you reach zero.
Return the node when the index is 0.
In this case you don't need to know anything about the parent of the node. So mating/mutation should look like this:
select nodeX
select nodeY
if( Rand(0,1) == 1 )
nodeY->left = nodeX;
else
nodeY->right = nodeX;
And that should be it...
I don't think the Node or the Tree are the first classes to write.
I'd start with Expression. In your case you need at least a BinaryExpression, as well as an expression with no subnodes (constants or variables). Each Binary expression should contain auto_ptr<Expression> lhs and auto_ptr<Expression> rhs.
You could then easily write a function to enumerate through the expression tree's members. If performance turns out to be relevant, you can cache the list of expressions in the tree, and invalidate it manually when you change the expression. Anything more advanced is likely to be slower and more error prone.
I don't see why an expression needs to know it's parent expression. It only makes life harder when you start editing expressions.
You may implement a list over nodes. Then, each node will have two additional pointers inside:
class Node{
...
Node* sequentialPrevious;
Node* sequentialNext;
...
}
And so will the tree:
class Tree{
...
Node* sequentialFirst;
Node* sequentialLast;
...
}
Than you will be albe to move bidirectionally over nodes just by jumping to sequentialFirst or sequentialLast and then iteratively to sequentialNext or sequentialPrevious. Of course, Node constructor and destructor must be properly implemented to keep those pointers up to date.