How to read file into a binary tree?
I need to read binary tree from a file then mirror it and write it out to another file. I have managed to mirror it, but can't find any way how to read it from file before mirroring. I have seen other people asking it, but none of them seem to get an answer.
#include <iostream>
using namespace std;
// Data structure to store a binary tree node
struct Node
{
int data;
Node *left, *right;
Node(int data)
{
this->data = data;
this->left = this->right = nullptr;
}
};
// Function to perform preorder traversal on a given binary tree
void preorder(Node* root)
{
if (root == nullptr) {
return;
}
cout << root->data << " ";
preorder(root->left);
preorder(root->right);
}
// Function to convert a given binary tree into its mirror
void convertToMirror(Node* root)
{
// base case: if the tree is empty
if (root == nullptr) {
return;
}
// convert left subtree
convertToMirror(root->left);
// convert right subtree
convertToMirror(root->right);
// swap left subtree with right subtree
swap(root->left, root->right);
}
int main()
{
/* Construct the following tree
1
/ \
/ \
2 3
/ \ / \
4 5 6 7
*/
Node* root = new Node(1);
root->left = new Node(2);
root->right = new Node(3);
root->left->left = new Node(4);
root->left->right = new Node(5);
root->right->left = new Node(6);
root->right->right = new Node(7);
convertToMirror(root);
preorder(root);
return 0;
}
With trees, recursive functions are usually the easiest way to go, since they allow you to iterate over the entire tree without having to manually maintain the state of the iteration.
For example, your Node::write() method (that you use to dump the state of your tree to disk) might look something like this (untested pseudocode):
void Node::write(FILE * fpOut) const
{
fprintf(fpOut, "BEGIN Node data=%i\n", data);
if (left) left->write(fpOut);
if (right) right->write(fpOut);
fprintf(fpOut, "END Node\n");
}
For example, for a tree that contains just the root (with data=1) and two children (with data=2 and data=3), that would result in a file that looks like this:
BEGIN NODE data=1
BEGIN NODE data=2
END NODE
BEGIN NODE data=3
END NODE
END NODE
... but how to read it back in? That's a bit trickier, but you can do that with a similar recursive function, something like this (again, untested pseudocode):
Node * readTree(Node * parent, FILE * fpIn)
{
char buf[128];
fgets(buf, sizeof(buf), fpIn);
while(strncmp(buf, "BEGIN NODE data=", 16) == 0)
{
Node * childNode = new Node(atoi(buf+16));
(void) readTree(childNode, fpIn); // recurse to read child node
if (parent)
{
if (parent->left == NULL) parent->left = childNode;
else if (parent->right == NULL) parent->right = childNode;
else
{
printf("File contains more than two children for node!?\n");
delete childNode; // avoid memory leak
break;
}
}
else return node; // return the root of the tree to the caller
}
return NULL;
}
Taking a page from the book of LISP, you could represent your tree as: (whitespace for clarity)
(1
(2
(4 * *)
(5 * *))
(3
(6 * *)
(7 * *)))
with a simple read function as:
Node * readTree(istream& is) {
std::istream::sentry s(is);
if (!s) {
// should not happen!
}
int data;
Node *left=nullptr, *right=nullptr;
if (is.peek() == '(') {
is.get(); // eat (
is >> data;
left = readTree(is);
right = readTree(is);
is.get(); // eat )
return TODO; // create Node from data, left, right
} else if (is.peek() == '*') {
is.get(); // eat *
return nullptr;
} else {
// should not happen!
}
}
We were given two structs, one representing a Player and another one representing a Task that the player can later implement after it has been assigned to him. Each player has a list of tasks sorted in ascending order. Initially we had to implement a circular doubly linked list with sentinel for the Players list and a singly sorted linked list with sentinel for the tasks (using the tasks_head & tasks_sentinel fields of the Players struct).
Once the data structures are set, we need to distribute the tasks from a given General tasks list (pointed to by Head_GL) to the players using a round robin algo (don't know if my solution is correct, haven't researched the algorithm so that i can try solving the problem on my own first).
The issue is that for some unknown to me reason, the program seems to hang when the isTaskListEmpty(..) is called and then the program stops just like that, without printing anything after cout<<"istasklist empty called";.
Any ideas on what i'm doing wrong?
P.S. I've never worked with c++ on anything other than simple hello world programs so my experience with pointers is beyond limited.
Header file declarations for the structs and some global variables:
/**
* Structure defining a node of the players double linked list
* tree
*/
struct Players
{
int pid; /*Player's identifier*/
int is_alien; /*Alien flag*/
int evidence; /*Amount of evidence*/
struct Players *prev; /*Pointer to the previous node*/
struct Players *next; /*Pointer to the next node*/
struct Tasks *tasks_head; /*Pointer to the head of player's task list*/
struct Tasks *tasks_sentinel; /*Pointer to the sentinel of player's task list*/
};
/**
* Structure defining a node of the tasks sorted linked list
*/
struct Tasks
{
int tid; /*Task's identifier*/
int difficulty; /*Task's difficulty*/
struct Tasks *next; /*Pointer to the next node*/
};
struct Head_GL
{
int tasks_count[3]; /*Count of tasks*/
struct Tasks *head; /*Pointer to the head of general list*/
};
/* Global variable, pointer to the head of the players list */
struct Players *players_head;
/* Global variable, pointer to the head of the tasks list */
struct Head_GL *tasks_head;
/* Global variable, pointer to the top of the completed task's stack */
struct Head_Completed_Task_Stack *tasks_stack;
/* Global variable, counter of the total num of tasks in the general tasks list */
int Total_Tasks;
Main.cpp:
/**
* #brief Optional function to initialize data structures that
* need initialization
*
* #return 1 on success
* 0 on failure
*/
int initialize() {
// players list init
players_head = (struct Players*) malloc(sizeof(struct Players));
players_head->evidence = -1;
players_head->is_alien = -1;
players_head->pid = -1;
players_head->next = NULL;
players_head->prev = NULL;
players_head->tasks_head = NULL;
players_head->tasks_sentinel = NULL;
// General Tasks List init
tasks_head = (struct Head_GL*) malloc(sizeof(struct Head_GL));
tasks_head->tasks_count[0] = 0;
tasks_head->tasks_count[1] = 0;
tasks_head->tasks_count[2] = 0;
tasks_head->head = NULL;
// Completed Tasks stack init
tasks_stack = (struct Head_Completed_Task_Stack*) malloc(sizeof(struct Head_Completed_Task_Stack));
tasks_stack->count = 0;
tasks_stack->head = NULL;
Total_Tasks = 0;
return 1;
}
/**
* #brief Distribute tasks to the players
* #return 1 on success
* 0 on failure
*/
int distribute_tasks() {
if(isDLLEmpty() || isGenTaskListEmpty()) return 0;
// round robin algo
int tasksToAssign;
struct Players* player = players_head->next; // start with the 1st player
struct Tasks* task = tasks_head->head; // start with the 1st task
// There's only one player and he's an impostor so exit
if(player->is_alien == 1 && player->next == NULL) return 0;
for(tasksToAssign = Total_Tasks; tasksToAssign > 0; tasksToAssign--) {
if(player->is_alien == 1 || player == players_head) {
tasksToAssign++;
player = player->next; // go to the next player
continue; // skip impostors
}
sortedInsertTaskList(&player,task->tid,task->difficulty);
player = player->next; // go to the next player
task = task->next; // go to the next task to assign
}
return 1;
}
// Beginning of General Tasks list implementation (Sorted singly linked list)
bool isGenTaskListEmpty() {
return (tasks_head->head == NULL);
}
int sortedInsertGenTaskList(int tid, int difficulty) {
// increment the list's difficulty counter
if (difficulty == 1) tasks_head->tasks_count[0]++;
else if (difficulty == 2) tasks_head->tasks_count[1]++;
else tasks_head->tasks_count[2]++;
Total_Tasks++; // increment the num of total tasks
struct Tasks *node = (struct Tasks*) malloc(sizeof(struct Tasks)); // could return null if not enough mem
if(node == NULL) return 0; // not enough memory exit
// add data to the new node
node->tid = tid;
node->difficulty = difficulty;
node->next = NULL;
if(isGenTaskListEmpty()) {
tasks_head->head = node;
return 1;
}
// insert the new node without breaking the sorting of the list
Tasks *curr = tasks_head->head;
while(curr->next != NULL && curr->next->difficulty < difficulty) {
curr = curr->next;
}
node->next = curr->next;
curr->next = node;
return 1;
}
void printGenTasksList() {
cout << "{" << tasks_head->tasks_count[0] << "," << tasks_head->tasks_count[1] << "," << tasks_head->tasks_count[2] << "}" << endl;
Tasks* curr = tasks_head->head;
do {
cout << "Task#" << curr->tid << ":" << curr->difficulty << endl;
curr = curr->next;
} while (curr != NULL);
}
// End of General Tasks list implementation (Sorted singly linked list)
// Beginning of Tasks List implementation (Sorted Singly Linked List w/sentinel)
bool isTaskListEmpty(struct Tasks* head) {
cout<<"istasklist empty called";
return (head->next == NULL);
}
int sortedInsertTaskList(struct Players** player, int tid, int difficulty) {
struct Tasks* node = (struct Tasks*) malloc(sizeof(struct Tasks)); // could return null if not enough mem
if(node == NULL) return 0;
// add data to the new node
node->tid = tid;
node->difficulty = difficulty;
node->next = NULL;
cout << "sortedInsert before is empty";
if (isTaskListEmpty((*player)->tasks_head)) { // if the list is empty, make the head and sentinel point to the new node
cout << "list was empty";
(*player)->tasks_head->next = node;
(*player)->tasks_sentinel->next = node;
return 1;
}
// check if the new node can be added to the end of the list
if ((*player)->tasks_sentinel->next->difficulty <= difficulty) {
(*player)->tasks_sentinel->next->next = node; // place new node at the end of the list
(*player)->tasks_sentinel->next = node; // update sentinel
return 1;
}
// insert the new node without breaking the sorting of the list
struct Tasks* curr = (*player)->tasks_head->next;
while (curr->next != NULL && curr->next->difficulty < difficulty) {
curr = curr->next;
}
node->next = curr->next;
curr->next = node;
return 1;
}
// End of Tasks List implementation (Sorted Singly Linked List w/sentinel)
// Beginning of players list implementation (circular doubly linked list w/ Sentinel)
bool isDLLEmpty() {
return (players_head->next == NULL);
}
int dllInsert(int pid, int isAlien) {
// allocate memory and initialize fields
struct Players* player = (struct Players*) malloc(sizeof(struct Players)); // could return null if not enough mem
if(player == NULL) return 0; // not enough memory, exit
player->pid = pid;
player->is_alien = isAlien;
player->evidence = 0;
player->prev = players_head;
player->tasks_head = NULL;
player->tasks_sentinel = NULL;
// check if the list is empty
if (isDLLEmpty()) {
player->next = players_head;
players_head->next = player;
players_head->prev = player;
return 1;
}
// insert the new player at the beginning of the list
players_head->next->prev = player;
player->next = players_head->next;
players_head->next = player;
return 1;
}
// End of players list implementation (circular doubly linked list w/ Sentinel)
I have a code that can determine tree height by hard coding it's values
I tried using container like structures but still was not successful, instead of posting what I have tried on the part of accepting tree nodes fro the Input which is actually messy,I decided to post the code with hard coded tree nodes, what I need is for the program to accept tree nodes from the keyboard with the following helper description for input
Input:
The first line is an integer N indicating the number of nodes.
For each of the next few lines, there are two integers include a and b.b is a child of a.
example:
5 // number of nodes
1 2
1 3
3 4
3 5
in which the height will be 3
// C++ program to find height of tree
#include <bits/stdc++.h>
using namespace std;
/* A binary tree node has data, pointer to left child
and a pointer to right child */
class node
{
public:
int data;
node* left;
node* right;
};
/* Compute the "maxDepth" of a tree -- the number of
nodes along the longest path from the root node
down to the farthest leaf node.*/
int maxDepth(node* node)
{
if (node == NULL)
return 0;
else
{
/* compute the depth of each subtree */
int lDepth = maxDepth(node->left);
int rDepth = maxDepth(node->right);
/* use the larger one */
if (lDepth > rDepth)
return(lDepth + 1);
else return(rDepth + 1);
}
}
/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
node* newNode(int data)
{
node* Node = new node();
Node->data = data;
Node->left = NULL;
Node->right = NULL;
return(Node);
}
// Driver code
int main()
{
node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
cout << "Height of tree is " << maxDepth(root);
return 0;
}
Since the input identifies the parent node by its data value, we need a helper function to find it:
node *findNode(node *node, int data)
{
if (!node) return 0;
if (node->data == data) return node;
class node *found;
(found = findNode(node->left, data)) || (found = findNode(node->right, data));
return found;
}
Then we can code the input processing, e. g.:
node *node, *root = 0; // initially empty
int nn, a, b;
cin>>nn;
while (cin>>a>>b)
{
if (!root)
root = newNode(a),
node = root;
else
node = findNode(root, a);
if (!node->left) node->left = newNode(b);
else node->right = newNode(b);
}
I am working on a linked list implementation in C++. I am making progress but am having trouble getting the insertion functionality and deletion functionality to work correctly. Below is list object in the C++ header file:
#ifndef linkList_H
#define linkList_h
//
// Create an object to represent a Node in the linked list object
// (For now, the objects to be put in the list will be integers)
//
struct Node
{
Node() : sentinel(0) {}
int number;
Node* next;
Node* prev;
Node* sentinel;
};
//
// Create an object to keep track of all parts in the list
//
class List
{
public:
//
// Contstructor intializes all member data
//
List() : m_listSize(0), m_listHead(0) {}
//
// methods to return size of list and list head
//
Node* getListHead() const { return m_listHead; }
unsigned getListSize() const { return m_listSize; }
//
// method for adding and inserting a new node to the linked list,
// retrieving and deleting a specified node in the list
//
void addNode(int num);
void insertNode(Node* current);
void deleteNode(Node* current);
Node* retrieveNode(unsigned position);
private:
//
// member data consists of an unsigned integer representing
// the list size and a pointer to a Node object representing head
//
Node* m_listHead;
unsigned m_listSize;
};
#endif
And here is the implementation (.cpp) file:
#include "linkList.h"
#include <iostream>
using namespace std;
//
// Adds a new node to the linked list
//
void List::addNode(int num)
{
Node *newNode = new Node;
newNode->number = num;
newNode->next = m_listHead;
m_listHead = newNode;
++m_listSize;
}
//
// NOTWORKING: Inserts a node which has already been set to front
// of the list
//
void List::insertNode(Node* current)
{
// check to see if current node already at
// head of list
if(current == m_listHead)
return;
current->next = m_listHead;
if(m_listHead != 0)
m_listHead->prev = current;
m_listHead = current;
current->prev = 0;
}
//
// NOTWORKING: Deletes a node from a specified position in linked list
//
void List::deleteNode(Node* current)
{
current->prev->next = current->next;
current->next->prev = current->prev;
}
//
// Retrieves a specified node from the list
//
Node* List::retrieveNode(unsigned position)
{
if(position > (m_listSize-1) || position < 0)
{
cout << "Can't access node; out of list bounds";
cout << endl;
cout << endl;
exit(EXIT_FAILURE);
}
Node* current = m_listHead;
unsigned pos = 0;
while(current != 0 && pos != position)
{
current = current->next;
++pos;
}
return current;
}
After running a brief test program in the client C++ code, here is the resulting output:
Number of nodes: 10
Elements in each node:
9 8 7 6 5 4 3 2 1 0
Insertion of node 5 at the list head:
4 9 8 7 6 5 4 9 8 7
Deletion of node 5 from the linked list
As you can see, the insertion is not simply moving node 5 to head of list, but is overwriting other nodes beginning at the third position. The pseudo code I tried to implement came from the MIT algorithms book:
LIST-INSERT(L, x)
next[x] <- head[L]
if head[L] != NIL
then prev[head[L]] <- x
head[L] <- x
prev[x] <- NIL
Also the deletion implementation is just crashing when the method is called. Not sure why; but here is the corresponding pseudo-code:
LIST-DELET'
next[prev[x]] <- next[x]
prev[next[x]] <- prev[x]
To be honest, I am not sure how the previous, next and sentinel pointers are actually working in memory. I know what they should be doing in a practical sense, but looking at the debugger it appears these pointers are not pointing to anything in the case of deletion:
(*current).prev 0xcdcdcdcd {number=??? next=??? prev=??? ...} Node *
number CXX0030: Error: expression cannot be evaluated
next CXX0030: Error: expression cannot be evaluated
prev CXX0030: Error: expression cannot be evaluated
sentinel CXX0030: Error: expression cannot be evaluated
Any help would be greatly appreciated!!
You have got an error in addNode(). Until you fix that, you can't expect insertNode to work.
Also, I think your design is quite silly. For example a method named "insertNode" should insert a new item at arbitrary position, but your method insertNode does a pretty different thing, so you should rename it. Also addNode should be renamed. Also as glowcoder wrote, why are there so many sentinels? I am affraid your class design is bad as a whole.
The actual error is that you forgot to set prev attribute of the old head. It should point to the new head.
void List::addNode(int num)
{
Node *newNode = new Node;
newNode->number = num;
newNode->next = m_listHead;
if(m_listHead) m_listHead->prev = newNode;
m_listHead = newNode;
++m_listSize;
}
Similarly, you have got another error in deleteNode(). It doesn't work when deleting last item from list.
void List::deleteNode(Node* current)
{
m_listSize--;
if(current == m_listHead) m_listHead = current->next;
if(current->prev) current->prev->next = current->next;
if(current->next) current->next->prev = current->prev;
}
Now you can fix your so-called insertNode:
void List::insertNode(Node* current)
{
int value = current->number;
deleteNode(current);
addNode(value);
}
Please note that I wrote everything here without compiling and testing in C++ compiler. Maybe there are some bugs, but still I hope it helps you at least a little bit.
In deleteNode, you are not handling the cases where current->next and/or current->prev is null. Also, you are not updating the list head if current happens to be the head.
You should do something like this:
node* next=current->next;
node* prev=current->prev;
if (next!=null) next->prev=prev;
if (prev!=null) prev->next=next;
if (m_listhead==current) m_list_head=next;
(Warning: I have not actually tested the code above - but I think it illustrates my idea well enough)
I am not sure what exactly your InsertNode method does, so I can't offer any help there.
OK.
As #Al Kepp points out, your "add node" is buggy. Look at Al's code and fix that.
The "insert" that you are doing does not appear to be a normal list insert. Rather it seems to be a "move to the front" operation.
Notwithstanding that, you need to delete the node from its current place in the list before you add it to the beginning of the list.
Update
I think you have misunderstood how insert should work. It should insert a new node, not one that is already in the list.
See below for a bare-bones example.
#include <iostream>
// List Node Object
//
struct Node
{
Node(int n=0);
int nData;
Node* pPrev;
Node* pNext;
};
Node::Node(int n)
: nData(n)
, pPrev(NULL)
, pNext(NULL)
{
}
//
// List object
//
class CList
{
public:
//
// Contstructor
//
CList();
//
// methods to inspect list
//
Node* Head() const;
unsigned Size() const;
Node* Get(unsigned nPos) const;
void Print(std::ostream &os=std::cout) const;
//
// methods to modify list
//
void Insert(int nData);
void Insert(Node *pNew);
void Delete(unsigned nPos);
void Delete(Node *pDel);
private:
//
// Internal data
//
Node* m_pHead;
unsigned m_nSize;
};
/////////////////////////////////////////////////////////////////////////////////
CList::CList()
: m_pHead(NULL)
, m_nSize(0)
{
}
Node *CList::Head() const
{
return m_pHead;
}
unsigned CList::Size() const
{
return m_nSize;
}
void CList::Insert(int nData)
{
Insert(new Node(nData));
}
void CList::Insert(Node *pNew)
{
pNew->pNext = m_pHead;
if (m_pHead)
m_pHead->pPrev = pNew;
pNew->pPrev = NULL;
m_pHead = pNew;
++m_nSize;
}
void CList::Delete(unsigned nPos)
{
Delete(Get(nPos));
}
void CList::Delete(Node *pDel)
{
if (pDel == m_pHead)
{
// delete first
m_pHead = pDel->pNext;
if (m_pHead)
m_pHead->pPrev = NULL;
}
else
{
// delete subsequent
pDel->pPrev->pNext = pDel->pNext;
if (pDel->pNext)
pDel->pNext->pPrev = pDel->pPrev;
}
delete pDel;
--m_nSize;
}
Node* CList::Get(unsigned nPos) const
{
unsigned nCount(0);
for (Node *p=m_pHead; p; p = p->pNext)
if (nCount++ == nPos)
return p;
throw std::out_of_range("No such node");
}
void CList::Print(std::ostream &os) const
{
const char szArrow[] = " --> ";
os << szArrow;
for (Node *p=m_pHead; p; p = p->pNext)
os << p->nData << szArrow;
os << "NIL\n";
}
int main()
{
CList l;
l.Print();
for (int i=0; i<10; i++)
l.Insert((i+1)*10);
l.Print();
l.Delete(3);
l.Delete(7);
l.Print();
try
{
l.Delete(33);
}
catch(std::exception &e)
{
std::cerr << "Failed to delete 33: " << e.what() << '\n';
}
l.Print();
return 0;
}
Given a binary search tree, i need to convert it into a doubly linked list(by traversing in zig zag order) using only pointers to structures in C++ as follows,
Given Tree:
1
|
+-------+---------+
| |
2 3
| |
+----+---+ +----+---+
| | | |
4 5 6 7
| | | |
+--+--+ +--+--+ +--+--+ +--+--+
| | | | | | | |
8 9 10 11 12 13 14 15
Node Structure:
struct node
{
char * data;
node * left;
node * right;
};
Create List(zig zag order):
1 <-> 3 <-> 2 <-> 4 <-> 5 <-> 6 <-> 7 <-> 15 <-> ... <-> 8
Could someone please help me out.
This is a Breadth-first search algorithm. Wikipedia has a good explanation on how to implement it.
After implementing the algorithm, creating your linked list should be a no-brainer (since it will only be a matter of appending each visited element to the list)
That's an awkward type of tree traversal. I wonder how often anyone has ever actually needed to do such a thing in real code. Nevertheless, it's the problem to be solved here...
Here's how I would approach dealing with this:
First, when I compare the desired output to the structure of the tree, I notice that each "level" of the tree is processed in turn from top to bottom. So top node first, then all child nodes, then all grand-child notes, and so on. So probably a good solution will involve a loop that processes one level and at the same time builds up a list of nodes in the next level to be used in the next iteration of the loop.
Next, this "zig zag" order means it needs to alternate which direction the child nodes are processed in. If a particular iteration goes from left to right, then the next iteration must go from right to left. And then back to left to right for the subsequent iteration and so on. So in my idea of a loop that processes one level and builds a list of the next level, it probably needs to have some sort of alternating behavior when it builds that list of nodes for the next level. On even iterations the list is built one way. On odd iterations the list is built the other way.
Alternatively, another other way to think about this whole thing is: Design a solution to that can build the result list in 1,2,3,4,5,6,etc order. Then modify that design to have the zig zag order.
Does this give you enough of an idea on how to design a solution?
This might help you:
Create a separate list for every level of the tree
Traverse the tree and copy the values to the lists as you traverse the tree
Reverse the order of every other list
Connect the lists
In this solution below I have used two stacks to store Levels alternatively.
say nodes at level 0 will be store in stack 1 whose name is head1;now pop the element while it not become empty and push the elements in stack 2.the order i.e left or right child of insertion will depend on the level.and change the insertion order at each level.
node * convert_to_dll(node *p)
{
static int level=0;
push_in_stack(p,&head1);
printf("%d\n",p->data);
while( head1!=NULL || head2!=NULL) {
//pop_from_queue(&headq);
if(head1!=NULL && head2==NULL) {
while(head1!=NULL) {
if(level%2==0) {
node *p;
p=new node;
p=pop_from_stack(&head1);
if(p->right!=NULL) {
push_in_stack(p->right,&head2);
printf("%d\n",(p->right)->data);
}
if(p->left!=NULL)
{
push_in_stack(p->left,&head2);
printf("%d\n",(p->left)->data);
}
}
}
//traverse_stack(head2);
level++;
} else {
while(head2!=NULL) {
if(level%2!=0) {
node *q;
q=new node;
q=pop_from_stack(&head2);
if(q->left!=NULL) {
push_in_stack(q->left,&head1);
printf("%d\n",(q->left)->data);
}
if(q->right!=NULL) {
push_in_stack(q->right,&head1);
printf("%d\n",(q->right)->data);
}
}
} //traverse_stack(head2);
level++;
}
}
return p;
}
you can write a function to add nodes in a doubly linked list. You can then call this function while traversing the tree. In this way you should be able to do it.
Hmm... This is a tough one. The problem with traversal in this order is that you are doing a lot of skipping around. This is generally true in any tree traversal order that is not depth or breadth first.
Here's how I would resolve the situation. Start with a single, empty array of lists of nodes and begin traversing the tree depth first. Be sure to keep track of the depth of your traversal.
At each point in traversal, note the depth of your traversal and pick the list at the index in the array. If there isn't one there, add it first. If the depth is even (Assuming root has depth 0), add the node to the end of the list. If it's odd, add it to the beginning.
Once you've traversed all nodes, concatenate the lists.
Why use pointers?? You could just store your BST as an array A[1...n]. So, A[1] would have root, A[2] and A[3] would have nodes of the depth 1, etc. This is possible since it is an almost complete tree, and you know how many elements will be present at a given depth - i.e. 2^d at depth d (except of course at the last depth). Now all you've got to do is access the array in a zag-zag manner, and create a new BST (array) of the new order. So, how would you traverse the array in a zig-zag manner?? For any given element A[i], the left child would be A[2i] and the right child A[2i + 1]. So, if your current depth d is odd, then traverse 2^d elements, and when you reach the 2^dth element, go to its left child. If your current depth d is even, again traverse 2^d elements, but when you reach the 2^dth element, go to its right child. Storing them as arrays rather than nodes makes your data structure leaner, and your implementation simpler.
This ( http://cslibrary.stanford.edu/109/TreeListRecursion.html) has the answer with pretty pictures :)
#include<iostream>
#include<conio.h>
using namespace std;
class TreeNode
{
public:
int info;
TreeNode* right;
TreeNode* left;
//TreeNode* parent;
TreeNode()
{
info = 0;
right = left = NULL;
}
TreeNode(int info)
{
this -> info = info;
right = left = NULL;
}
};
class ListNode
{
public:
int info;
ListNode* next;
ListNode()
{
info = 0;
next = NULL;
}
ListNode(int info)
{
this -> info = info;
next = NULL;
}
};
TreeNode* root = NULL;
ListNode* start;
ListNode* end;
void addTreeNode(TreeNode*);
void convertTreeToList(TreeNode*);
void printList(ListNode*);
int findDepth(TreeNode*);
int _tmain(int argc, _TCHAR* argv[])
{
start = end = new ListNode(0);
char choice = 'y';
int info;
while(choice == 'y')
{
cout<<"Enter the info of new node:\n";
cin>>info;
addTreeNode(new TreeNode(info));
cout<<"Want to add a new node to the tree?(y/n)\n";
cin>>choice;
}
cout<<"Depth of the tree is: "<<findDepth(root);
cout<<"Converting the tree into a doubly linked list....\n";
convertTreeToList(root);
printList(start->next);
cin>>choice;
return 0;
}
void addTreeNode(TreeNode* node)
{
if(!root)
{
root = node;
}
else
{
TreeNode* currRoot = root;
while(1)
{
if(node -> info >= currRoot -> info)
{
if(!currRoot -> right)
{
currRoot -> right = node;
break;
}
else
{
currRoot = currRoot -> right;
}
}
else
{
if(!currRoot -> left)
{
currRoot -> left = node;
break;
}
else
{
currRoot = currRoot -> left;
}
}
}
}
}
void convertTreeToList(TreeNode* node)
{
if(node -> left != NULL)
{
convertTreeToList(node -> left);
}
end ->next = new ListNode(node -> info);
end = end -> next;
end -> next = start;
if(node -> right != NULL)
{
convertTreeToList(node -> right);
}
}
void printList(ListNode* start)
{
while(start != ::start)
{
cout<<start->info<<" -> ";
start = start -> next;
}
cout<<"x";
}
int findDepth(TreeNode* node)
{
if(!node)
{
return 0;
}
else
{
return (max(findDepth(node -> left), findDepth(node -> right)) + 1);
}
}
Linked list you get here is singly linked and sorted. Hope you can easily make changes in this code to get a doubly linked list. Just copy - paste this code and compile it.It will work fine.
Let us assume that the root of the binary tree is at level 0(an even number). Successive levels can be considered as alternating between odd even (children of root are at odd level, their children are at even level etc.). For a node at even level, we push its children onto a stack(This enables reverse traversal). For a node at odd level, we push its children onto a queue(This enables forward traversal). After children have been pushed, we remove the next available element (top of stack or front of queue) and recursively call the function by changing level to odd or even depending on where the removed element lies. The removed element can be inserted at the end of the doubly linked list. Pseudo-code below.
// S = stack [accessible globally]
// Q = queue [accessible globally]
//
// No error checking for some corner cases to retain clarity of original idea
void LinkNodes(Tree *T,bool isEven,list** l)
{
if(isEven) {
S.push(T->right);
S.push(T->left);
while( !S.empty() ) {
t = S.pop();
InsertIntoLinkedList(l,t);
LinkNodes(t,!isEven);
}
} else {
Q.enque(T->left);
Q.enque(T->right);
while( !Q.empty() ) {
t = Q.deque();
InsertIntoLinkedList(l,t);
LinkNodes(t,isEven);
}
}
}
In the calling function:
bool isEven = true;
list *l = NULL;
// Before the function is called, list is initialized with root element
InsertIntoLinkedList(&l,T);
LinkNodes(T,isEven,&l);
/* * File: main.cpp * Author: viswesn * * Created on December 1, 2010, 4:01 PM */
struct node {
int item;
struct node *left;
struct node *right;
struct node *next;
struct node *prev;
};
struct node *dlist = NULL;
struct node *R = NULL;
struct node* EQueue[10] = {'\0'};
int Etop = 0;
struct node* OQueue[10] = {'\0'};
int Otop = 0;
int level=-1;
struct node *insert(struct node *R, int item)
{
struct node *temp = NULL;
if (R != NULL) {
if (item < R->item) {
R->left = insert(R->left, item);
} else {
R->right = insert(R->right, item);
}
} else {
temp = (struct node *)malloc(sizeof(struct node));
if (temp == NULL) {
return NULL;
}
temp->item = item;
temp->left = NULL;
temp->right = NULL;
temp->next = NULL;
temp->prev = NULL;
R = temp;
}
return R;
}
void print(struct node *node)
{
if (node != NULL) {
print(node->left);
printf("%d<->", node->item);
print(node->right);
}
}
void EvenEnqueue(struct node *item) {
if (Etop > 10) {
printf("Issue in EvenEnqueue\n");
return;
}
EQueue[Etop] = item;
Etop++;
}
void OddEnqueue(struct node *item)
{
if (Otop > 10){
printf("Issue in OddEnqueue\n");
return;
}
OQueue[Otop] = item;
Otop++;
}
int isEvenQueueEmpty() {
if (EQueue[0] == '\0') {
return 1;
}
return 0;
}
int isOddQueueEmpty()
{
if (OQueue[0] == '\0') {
return 1;
}
return 0;
}
void EvenDQueue()
{
int i = 0;
for(i=0; i< Etop; i++)
EQueue[i]='\0';
Etop = 0;
}
void OddDQueue()
{
int i = 0;
for(i=0; i< Otop; i++)
OQueue[i]='\0';
Otop = 0;
}
void addList() {
int counter = 0;
struct node *item = NULL;
if (level%2 == 0) {
/* Its Even level*/
while(counter < Etop)
{
struct node *t1 = EQueue[counter];
struct node *t2 = EQueue[counter+1];
if ((t1!=NULL) && (t2!=NULL)) {
t1->next = t2;
t2->prev = t1;
}
counter++;
}
item = EQueue[0];
} else {
/* Its odd level */
while(counter < Otop)
{
struct node *t1 = OQueue[counter];
struct node *t2 = OQueue[counter+1];
if ((t1!=NULL) && (t2!=NULL)) {
t2->next = t1;
t1->prev = t2;
}
counter++;
}
item = OQueue[Otop-1];
}
if(dlist !=NULL) {
dlist->next = item;
}
item->prev = dlist;
if (level%2 == 0) {
dlist = EQueue[Etop-1];
} else {
dlist = OQueue[0];
}
}
void printTree()
{
int nodeCount = 0;
int counter = 0;
if (!isEvenQueueEmpty()) {
/* If even level queue is not empty */
level++;
nodeCount = pow(2,level);
printf("[");
while(counter < nodeCount) {
if (EQueue[counter] != '\0') {
struct node *t = EQueue[counter];
printf("%d<->", t->item);
if (t->left != NULL)
OddEnqueue(t->left);
if (t->right != NULL)
OddEnqueue(t->right);
} else {
break;
}
counter++;
}
addList();
printf("]");
EvenDQueue();
}
counter = 0;
if (!isOddQueueEmpty()){
/* If odd level queue is not empty */
level++;
nodeCount = pow(2,level);
printf("[");
while(counter < nodeCount){
if (OQueue[counter] != '\0') {
struct node *t = OQueue[counter];
printf("%d<->", t->item);
if (t->left != NULL)
EvenEnqueue(t->left);
if (t->right != NULL)
EvenEnqueue(t->right);
} else {
break;
}
counter++;
}
addList();
printf("]");
OddDQueue();
}
if (isEvenQueueEmpty() && isOddQueueEmpty()){
return;
}
else {
printTree();
}
}
void printLevel(struct node *node)
{
if (node == NULL)
return;
EvenEnqueue(node);
printTree();
printf("\n");
}
void printList(struct node *item)
{
while(item!=NULL) {
printf("%d->", item->item);
item = item->next;
}
}
int main(int argc, char** argv) {
int a[]={20,30,40,12,2,15,18};
int size = sizeof(a)/sizeof(int);
int i = 0;
for(i=0; i< size; i++) {
R = insert(R, a[i]);
}
printf("Inoder traversal - Binary tree\n");
print(R);
printf("\n\n");
printf("Level traversal - Binary tree\n");
printLevel(R);
printf("\n");
printf("Double link list traversal - Binary tree\n");
printList(R);
printf("\n");
return 0;
}