I'm currently working on building a non-binary tree that takes I/O to build the branches of the tree. I have number of issues I need to work out though and some pseudo code that I don't know how to turn into C++. For starters this is the structure of the nodes for the tree.
// Code for the structure of a node
typedef string Elem;
struct Node
{
int nodeID; // Node ID number
Elem value; // Value contains a string for each node
Node* parent; // A pointer to the parent of a node
vector<Node>* child; // A pointer to a vector which holds the children
};
Here also is the header file for the Tree class. The root_ private member is a pointer to the root of the tree and the current_ pointer points to whatever node you're currently working with. Size_ is simply an in that is incremented with the insertion or deletion of each node.
// Header file for Tree class
class AnimalTree
{
public:
AnimalTree() { root_ = NULL; }
~AnimalTree() {};
void currentNode() const; // Returns current node ID & value
void parent() const; // Return parent ID & value of current
vector<Node> children() const; // Return the ID & value of each node in current
int size() const; // Return size of tree
bool empty() const; // Return true if empty
void root() const; // Get the root ID & value
bool isLeaf() const; // Return true if current node is a leaf
bool isRoot() const; // Return true if current node is root
void searchNodeString(string val); // Search for a particular node by it's string value
private:
Node* root_;
Node* current_;
int size_;
};
Here are my questions:
Is it possible to use my node struct as input in a class function for a tree? And if so how could I implement it in something like a search function to find a specific node?
As part of a search function how would you index the child vector of a parent node? Or in C++ code, how would you search through each node in a child vector individually?
Is there a better way to use the pointers on each node to traverse the tree? I've seem to run into issues when moving from node to node when using the parent node pointer to the child vector of nodes pointer.
In C++ how do you traverse a non-binary tree? Whether it be pre-order or post-order.
Related
I have implemented a simple binary tree class in C++.
have using smart pointers objects to hold the pointers to each node (shared for children and weak for parent).
I was trying to implement a nested class for custom iterator (in-order, pre-order and post-order), but I couldn't figure out how to implement efficiently the .next() method.
how can I get current position in traversal without holding the entire tree in a priority queue.
the tree nodes are a struct -
struct node : std::enable_shared_from_this
{
T _val;
std::weak_ptr<node> _parent;
std::shared_ptr<node> _leftChild;
std::shared_ptr<node> _rightChild;
// CONSTRUCTORS
node(T val): _val(val){}
node(T val, weak_ptr<node> parent): _val(val), _parent(parent){}
};
You need to know which child each node is, and from that you can derive the next node from the structure. You can do that with pointer equality
struct iter_base {
std::shared_ptr<node> current;
bool isRoot() const { return !current->_parent.lock(); }
bool isLeft() const { auto parent = current->_parent.lock(); return parent && (current == parent->_leftChild); }
bool isRight() const { auto parent = current->_parent.lock(); return parent && (current == parent->_rightChild); }
};
E.g. for inorder:
If you have a right child, follow that node's left descendants until there are no more, the last one is the next node.
Otherwise, if you are a left child, the next node is your parent.
Otherwise, if you are a right child, follow parent pointers until you find one that is a left child, and the next node is the parent of that left child. You've reached the end if you get to the root doing this.
I am studying generic binary search trees (BST) and AVL trees (AVL) on some notes that contain implementation pseudocodes. I am a bit puzzled about some details of their implementation.
The BST is based on the struct Node below
struct Node{
int key;
Node* parent;
Node* left;
Node* right;
//constructors
}
//methods
The AVL version is basically the same with a few fields more for balancing the tree (I'll call it AVLNode for clarity, but there's no such distinction on the notes):
struct AVLNode{
int key;
int height;
int size;
AVLNode* parent;
AVLNode* leftchild;
AVLNode* rightchild;
//constructors
}
//methods
A lot of operations are the same between the two trees and I can easily use templates in order to reuse them on both trees. However, consider the operation insert, which inserts a new node. The code for a BST is something like
//Insert node with key k in tree with root R
void insert(const int& k, Node* root){
Node* N=find(k, root); //finds where to insert the node
if (N->key>k)
N->leftchild=new Node(k,N); //inserts as a left child
else
N->rightchild=new Node(k,N); //inserts as a right child
}
Now, the point is that the insert operation of an AVL tree is basically the same. The pseudocode presented in the notes is as follows:
void avlInsert(int k, AVLNode* R){
insert(k,R); //same operations as for Nodes, shown above
AVLNode* N=find(x,R); //find node inserted (generic operation for BST)
rebalance(N); //perform balancing operations specific to AVL trees
}
I'm a bit puzzled at this point, I know that the above is just a pseudocode but I was wondering whether there is a way to reuse the operation insert already provided for Node. Using template specialization would just mean writing a different specialization insert<AVLNode> for AVLNode, so that's not what I'm referring to.
I think a way would be to define AVLNode as a child class of Node and then use something like
struct AVLNode : Node {
//implementation
}
void avlInsert(int k, AVLNode* R){
Node *root=R;
insert(k,root);
AVLNode* N=find(x,R);
rebalance(N);
}
but I'm not quite sure this would work and I don't know how to manage the pointers to parent and the childs (i.e. they must be pointers to Node inside Node and to AVLNode inside AVLNode).
Is there a way to avoid rewriting the same code?
You could use CRTP here. This would allow you to create the left right and parent nodes in the baseclass. For example consider something like this:
template<typename T>
struct BaseNode{
int key;
T* parent;
T* left;
T* right;
};
struct AVLNode : public BaseNode<AVLNode>{
int height;
int size;
AVLNode(const int&k, AVLNode*root){};
AVLNode(){};
};
struct Node : public BaseNode<Node>{
Node(const int&k, Node*root){};
Node(){};
};
template<typename T>
T* find(const int& k, T* root){return root;};
template<typename T>
void insert(const int& k, T* root){
T* N=find(k, root); //finds where to insert the node
if (N->key>k)
N->left=new T(k,N); //inserts as a left child
else
N->right=new T(k,N); //inserts as a right child
}
void test(){
AVLNode avl_root;
Node node_root;
insert(42, &avl_root);
insert(42, &node_root);
}
The downside is that the compiler will generate more code than necessary. Because it creates a new insert function for every type. This might not be a problem for you, but something worth considering. See godbolt for the generated code.
As an aside. Please please please please don't use raw pointers and new and delete. You'll be going to get so many memory leaks, especially if a pointer gets "lost" because its parent gets deleted. Consider using smart pointers like unique_ptr or shared_ptr
I'm working on my final project for C++ and my professor specified that we had to have three class files for a linked list.
The first named LinkedList holds the head and the tail, as well as two overloaded operators in which we have to use the list as an array, and add an element to the end of the array.
The second named Node holds the two generic values Seat and Row.
The third and final named RNode holds the values of the next, previous spots in the list, as well as reservation status.
My problem is when using my LinkedList.cpp, defining all of the functions, I cannot figure out how to set node equal to the head, because the types are different. I can set the next node in the list with tempNode.setNext(Head);. But when I try to do tempNode = tempNode.getNext() it says the types are not the same. What is an easy way for me to make this work?
Here is my code.
This is supposed to use the Linked List as an array and return the pointer to the Node correlating with the integer passed in.
int& LinkedList::operator[] (const int &middle) {
RNode *tempNode;
tempNode->setNext(Head);
tempNode = tempNode->getNext(); // Error here
for (int i = 0; i < middle; i++) {
}
}
Here are the three class files I have currently made.
Linked List Class
#ifndef LINKEDLIST_H_INCLUDED
#define LINKEDLIST_H_INCLUDED
#include "Node.h"
class LinkedList {
private:
Node* Head; // Head of linked list
Node* Tail; // Tail of linked list
public:
// Constructors
LinkedList(); // Set default values
LinkedList(Node*, Node*); // Set values passed in to head and tail
int& operator [] (const int &); // Overloaded [] operator PAGE 854 HOW TO USE THIS
// Treat list like an array.
// First node will be [0]
// Return pointer to node indicated inside of brackets
Node& operator += (const Node &); // Overloaded += operator
// Adds a node to the end of the linked list
// Head
void setHead(Node*); // Sets head of list
Node* getHead(); // Returns the head of list
// Tail
void setTail(Node*); // Sets tail of list
Node* getTail(); // Returns tail of list
};
#endif // LINKEDLIST_H_INCLUDED
Reservation Node Class
#ifndef RNODE_H_INCLUDED
#define RNODE_H_INCLUDED
#include "Node.h"
using namespace std;
class RNode : public Node {
private:
Node* Next; // Next node pointer
Node* Prev; // Previous node pointer
bool reservationStatus(); // Reservation status
public:
// Constructors
RNode(); // Sets default values
RNode(Node*, Node*, bool); // Takes values passed in and sets them
// Overloaded operators
friend ostream &operator << (ostream &, Node*); // Prints out correct symbol based on reservation status
friend istream &operator >> (istream &, Node*); // Prints correct symbol based on reservation status .
// Next
void setNext(Node*); // Sets next node in list
Node* getNext(); // Returns next node in list
// Prev
void setPrev(Node*); // Sets previous node in list
Node* getPrev(); // Returns previous node in list
// Reservation Status
void setReservationStatus(bool); // Sets reservation status of a current node
bool getReservationStatus(); // Returns reservation status
};
#endif // RNODE_H_INCLUDED
Node Class
#ifndef NODE_H_INCLUDED
#define NODE_H_INCLUDED
class Node {
protected:
int row;
int seat;
public:
// Constructors
Node(); // Sets default values
Node(int, int); // Sets row and seat to values passed in
// Row
void setRow(int); // Sets row for current node
int getRow(); // Gets row for current node
// Seats
void setSeat(int); // Sets seat for current node
int getSeat(); // Gets seat for current node
};
#endif // NODE_H_INCLUDED
In summary, how can I match the types so that I can set RNode tempNode equal to a Node? This is very confusing and I can't really find a good explanation on how to solve this.
Keep in mind, according to my instructions I have to have the classes created this way. If it were up to me, I would have combined the RNode and Node class.
I keep finding myself wanting to do things the right way™. However, I am a bit confused about data encapsulation (not the principle of it, but how to do it correctly in C++)
Let's say I have the following class:
template <class T, class Alloc = std::allocator<T> >
class Tree
{
public:
class Node
{
public:
T data;
Node** get_children() const { return children; }
Node* get_parent() const { return parent; }
Node* get_right() const { return right; }
friend class Tree;
private:
Node** children;
Node* parent;
Node* right;
};
// typedefs for STL ...
class iterator // linear iterator
{
// ...
};
class const_iterator // linear iterator
{
// ...
};
// Tree operations ...
private:
Node root;
};
I want the tree to be able to modify the structure of the nodes freely, so I made it a friend class to the node.
I also want the user to be able to traverse the tree as a tree (rather than using the tree structure for storage behind the scenes, and just letting the user iterate over it linearly).
The data should be freely modifiable. If the owner of the tree object doesn't want another user to modify its contents, it can pass a const reference.
Now I'm left wondering about the return types of my getter methods. Whatever happens, I don't want the user ever to be able to change the structural information of the node directly. The tree should always be the one modifying the private members. Will this code guarantee that? What if instead of a Node**, we save a std::vector<Node*> and return a const reference to the vector?
These two are secure:
Node* get_parent() const { return parent; }
Node* get_right() const { return right; }
Since these functions return pointers by value, the user cannot modify the member variables.
This one is unsafe:
Node** get_children() const { return children; }
This too returns a pointer by value, so that the user cannot modify children, but the user can modify the elements in the array, which I presume are pointers to children. Here's how to make it safe:
Node * const * get_children() const { return children; }
(And when you're ready, you can advance to STL containers and stop using arrays.)
A simple binary search tree class declaration:
#include <vector>
#include <stdio.h>
// Provides various structures utilized by search algorithms.
// Represents an generalized node with integer value and a set of children.
class Node {
protected:
std::vector<Node*> children;
int value;
public:
//Creates a new instance of a Node with a default value=-1.
Node(){value = -1;}
//Creates a new instance of a Node with a specified value.
explicit Node(int value){this->value = value;}
virtual ~Node(){delete children;}
//Adds new Node with specified value to the list of child nodes. Multiple
//children with the same value are allowed.
//Returns added node.
virtual Node* Insert(int value);
//Removes first occurrence of a Node with specified value among children.
virtual void Remove(int value);
};
// Represents a binary search tree node with at most two children.
class BTNode: public Node {
public:
//Creates a new instance of a BTNode with a default value=-1.
BTNode():Node(){}
//Creates a new instance of a BTNode with a specified value.
explicit BTNode(int value):Node(value){}
//Adds new BTNode with specified value to the list of child nodes in an
//ordered manner, that is right child value is >= value of this node and
//left child value < value of this node.
virtual BTNode* Insert(int value);
//Removes first occurrence of a Node with specified value from the tree.
virtual void Remove(int value);
//Returns a node with specified value.
virtual BTNode* Search(int value);
};
And eclipse complains about it's definition:
BTNode* BTNode::Search(int value){
if (this->value == value) return *this;
//Determines whether value is in left(0) or right(1) child.
int child = this->value > value ? 0 : 1;
if (children[child] != NULL)
return children[child]->Search(value);
return NULL;
}
exactly where the call children[child]->Search(value) takes place with a message "method Search could not be resolved". Build runs just fine (no compilation errors whatsoever). What's the problem with that?
P.S.:Haven't tried running the code,yet. Working on it.
Search is part of the BTNode interface but it is not part of Nodes interface, children is a vector of Node* so it is not valid to call Search on a Node *. If it makes sense for Node to have a Search method then adding it to Node would fix that issue. If not then you need to rethink your design and that is probably beyond the scope of this question.
There are also a few other issues. You have:
virtual ~Node(){delete children;}
but children is not a pointer it is a std::vector<Node*>. You need to iterate over the vector and call delete each element. In Search you have this:
if (this->value == value) return *this;
but Search returns a BTNode* so it should be:
if (this->value == value) return this ;