N-ary Tree Level Traversal bug (C++) - c++

I'm doing a coding challange on LeetCode and I'm asked to traverse each level and at the end return a nested vectors with values node values for each values.
So if I have a tree like:
Which is
Input: root = [1,null,3,2,4,null,5,6]
And expected output is
Output: [[1],[3,2,4],[5,6]]
The definition for the Node is as follows:
/*
// Definition for a Node.
class Node {
public:
int val;
vector<Node*> children;
Node() {}
Node(int _val) {
val = _val;
}
Node(int _val, vector<Node*> _children) {
val = _val;
children = _children;
}
};
*/
I'm attempting an iterative solution that is as follows:
class Solution {
public:
vector<vector<int>> answer;
stack<Node*> nodes;
vector<vector<int>> levelOrder(Node* root) {
if(root == NULL)
return answer;
nodes.push(root);
answer.push_back(vector<int>() = {root->val});
while(!nodes.empty())
{
Node* curr = nodes.top();
nodes.pop();
vector<int>temp;
for(int i = 0; i < curr->children.size(); i++)
{
nodes.push(curr->children[i]);
temp.push_back(curr->children[i]->val);
}
if(temp.size() != 0)
answer.push_back(temp);
}
return answer;
}
};
However it consistently fails 20th test case where the input is:
[1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
The expectation is:
[[1],[2,3,4,5],[6,7,8,9,10],[11,12,13],[14]]
My output is
[[1],[2,3,4,5],[9,10],[13],[8],[12],[6,7],[11],[14]]
I'm having trouble visualising and drawing this N-ary tree on paper, so I have a hard time comprehending where my algorithm went wrong.

The problem with your code is that for each node you visit, you append all its children as a new list to the answer list. Your code does not group children on the same level but with different parents into one list, as would be expected by the solution.
Let us step through your code to see what happens:
Before the loop, you push the root node onto the stack and push a singleton set with the root node value to the answer:
stack = {1}
answer = { {1} }
The first iteration pops the 1 from the stack. You then iterate over the children 2,3,4,5, which are pushed on the stack. Afterwards, the list of children is pushed to the answer list.
stack = {2,3,4,5}
answer = { {1}, {2,3,4,5} }
The next iteration pops the 5 from the stack. You then iterate over the children 9, 10. They are pushed onto the stack. Afterwards, the list of children is pushed to the answer list.
stack = {2,3,4,9,10}
answer = { {1}, {2,3,4,5}, {9, 10} }
The next iteration pops the 10 from the stack. It has no children, so nothing happens.
stack = {2,3,4,9}
answer = { {1}, {2,3,4,5}, {9, 10} }
The next iteration pops the 9 from the stack. You then iterate over the single child 13, which is pushed to the stack. A singleton list containing 13 is pushed to the answer set.
stack = {2,3,4}
answer = { {1}, {2,3,4,5}, {9, 10}, {13} }
The next iteration pops the 4 from the stack. You then iterate over the single child 8, which is pushed to the stack. A singleton list containing 8 is pushed to the answer set.
stack = {2,3,8}
answer = { {1}, {2,3,4,5}, {9, 10}, {13}, {8} }
Your can see that your answer list is wrong from here. The 8 is on the same level as 9 and 10, so it should have been added to the {9,10} sub-list in the answer list, instead of creating a new list {8}. This should be sufficient to illustrate the problem, so I will not step through the code further.
To ensure that nodes on the same level are grouped into the same sub-list in the answer list, we have to keep track of the current level when visiting each node. We can do this by extending the stack to hold pairs of the current node and its depth. Each node value at depth d will then be appended to the dth sub-list in the answer list. This ensures that nodes on the same level are grouped into one sub-list.
std::vector<std::vector<int>> get_vals_per_level(const Node *root) {
std::vector<std::vector<int>> vals_per_level{};
std::stack<std::pair<const Node *, int>> stack{};
stack.emplace(root, 0);
while (!stack.empty()) {
auto [current, depth]{stack.top()};
stack.pop();
if (vals_per_level.size() == depth) {
vals_per_level.emplace_back();
}
// Append node value to the answer list for the current depth
vals_per_level[depth].push_back(current->val);
auto& children{current->children};
for (auto it{children.rbegin()}; it != children.rend(); it++) {
stack.emplace(*it, depth + 1);
}
}
return vals_per_level;
}
The code uses structured bindings from C++17.

Related

Subclass Mess on a vague Binary Tree Question

So, I'm taking data structures and algorithms and I'm trying to answer the following question:
(20 marks) Exercise 6.7. Create a subclass of BinaryTree whose nodes have fields for storing preorder, post-order, and in-order numbers. Write methods preOrderNumber(), inOrderNumber(), and postOrderNumbers() that assign these numbers correctly. These methods should each run in O(n) time.
Now... I'm confused about what the question is even asking. Are they asking me to store an array in each Node that records the preOrder, inOrder and postOrder values of the whole tree??? Or are they asking me to create a subclass of Node that contains an integer that's hold the Next value, according to a preOrder, inOrder or postOrder value, relative to the Node we're in...
So, I went with the former and assumed that they wanted the array. But the trouble now is that I've created a new version of Node and I'm trying to call this preOrderNumber() function at the bottom but I get the following error:
BTNode.h contains the code I used in a previous question to construct a binary tree. It just defines a class Node with a left, right, and parent pointer, as well as an add() function to add new values to the tree, and a preOrderNEXT() function that gets the next value in the tree according to that transversal order. the same is true for inOrderNEXT(), and postOrderNEXT()
#include <iostream>
#include "BTNode.h"
#include <vector>
using namespace std;
class BinaryTree : public Node {
public:
vector<int> preOrderNumbers;
vector<int> inOrderNumbers;
vector<int> postOrderNumbers;
BinaryTree(int x);
~BinaryTree();
int preOrderNumber();
int inOrderNumber();
int postOrderNumber();
};
BinaryTree::BinaryTree(int x) : Node(x) {}
BinaryTree::~BinaryTree() {}
int BinaryTree::preOrderNumber() {
Node* next_Node = preOrderNEXT(this);
while (next_Node != NULL) {
preOrderNumbers.push_back(next_Node->data);
next_Node = preOrderNEXT(next_Node);
}
}
int BinaryTree::inOrderNumber() {
Node* next_Node = inOrderNEXT(this);
while (next_Node != NULL) {
inOrderNumbers.push_back(next_Node->data);
next_Node = inOrderNEXT(next_Node);
}
}
int BinaryTree::postOrderNumber() {
Node* next_Node = postOrderNEXT(this);
while (next_Node != NULL) {
postOrderNumbers.push_back(next_Node->data);
next_Node = postOrderNEXT(next_Node);
}
}
int main() {
Node* BinaryT = new BinaryTree(rand() % 1000);
int arr[] = { 71, 6, 28, 49, 41, 42, 88, 72, 21, 84, 85, 94, 59, 29, 2, 97, 33, 23, 78 };
cout << "We add these integers, one by one, using a for loop to the binary tree:\n" << endl;
cout << "[ 60, ";
for (int i = 0; i < (sizeof(arr) / sizeof(arr[0])); i++) {
BinaryT->add(arr[i]);
cout << arr[i] << ", ";
}
int x = BinaryT->preOrderNumber();
}
OKAY, So yea I think I found out the real crux of this question and I'll answer this here for anyone else stuck in this situation.
The key to making sense out of this question is to visit its location in the textbook. The course coordinator ripped this question out of the textbook and doesn't provide any context. In Pat Morin's book Open Data Structure, An Introduction, on page 149 there's an illustration 6.10.
So, what this question IS ACTUALLY ASKING you to do is write a subclass for the Binary Tree Nodes such that each Node holds an integer that keeps track of its position within the corresponding traversal type. So maybe your Node would be visited 3rd in preOrder, 4th in an inOrder, and 2nd in a postOrder traversal. So that Node should hold a 3, a 4, and a 2 in the corresponding position. And then you need a function to update that position in O(n) time.

Huffman Tree, recursive function crashes (pointers are not relayed correctly)

struct node {
float weight;
char value;
node* left_child;
node* right_child;
};
void get_codes(node tree, std::string code, std::map<char, std::string> &codes)
{
if(!tree.left_child && !tree.right_child) // leap node
codes[tree.value] = code;
else
{
get_codes(*tree.left_child, code + "0", codes);
get_codes(*tree.right_child, code + "1", codes);
}
}
int main()
{
std::string test {"this is an example of a huffman tree"};
std::vector<char> alphabet = get_alphabet(test);
std::vector<float> weights = get_weights(test, alphabet);
std::priority_queue<node, std::vector<node>, is_node_greater> heap;
for(int i=0; i<alphabet.size(); i++)
{
node x;
x.weight = weights[i];
x.value = alphabet[i];
x.left_child = nullptr;
x.right_child = nullptr;
heap.push(x);
}
while(heap.size() > 1) {
node fg = heap.top(); heap.pop();
node fd = heap.top(); heap.pop();
node parent;
parent.weight = fg.weight + fd.weight;
parent.left_child = &fg;
parent.right_child = &fd;
heap.push(parent);
}
node tree = heap.top(); // our huffman tree
std::map<char, std::string> codes;
get_codes(tree, "", codes);
}
In the first loop, I build a heap (a priority queue) containing all the leap nodes, ie no left child, no right child (nullptr).
In the second loop, while the heap contains more than one node, I take the two with the smallest weights and I create a parent node with these two nodes as children. The parent node's weight is the sum of the two children's.
Then I have my huffman tree, and I have to get huffman codes. That is to say, I need to get a binary code for each leap node assuming bit '0' represents following the left child and bit '1' represents following the right child.
That's what my function get_codes should do, and where the crash occurs. It never enters the 'if' statement so recursivity never stops, so I think either it never comes to leap nodes but it should because each time the function is called on a child tree ; or the leap nodes/nullptr have been lost..? I'm new at C++ so I'm not very experienced with pointers, but this is how I would do the function in an other language.

C++ Pointers and Data Locations: Data Always Being Placed at Same Memory Location

I'm trying to implement an iterative deepening depth first search algorithm in C++. The search successfully finds the solution to the problem, but I am having trouble linking the child node back to the root node.
struct Node
{
std::vector<int> config;
int depth;
int action; //0 up 1 down 2 left 3 right
Node * parent;
bool operator<(const Node& rhs) const
{
return depth < rhs.depth;
}
};
As you can see in my structure, I have a pointer to the parent node. In my DFS code however, I am running into a problem updating the parent pointer for the nodes in each iteration of the loop. The parent pointer for all nodes always points to the same data location, 0xfffffffd2b0. In other words, the new node called Next is always created here.
I believe the Node I have in my code called Next always gets placed at this same data locataion, thus the reference location to each Next is always the same. How can I prevent it from always appearing at the same location? This means that the Child nodes are not being linked to their parent, but rather to themselves. I have marked the source of the bug with asterisks.
//IDDFS Logic:
int Current_Max_Depth = 0;
while(Current_Max_Depth < 20)
{
struct Node initial = {orig_config, 0, 0, NULL}; //config, depth, action, parent.
visited.clear();
priority_queue<Node> frontier;
frontier.push(initial);
while(frontier.size()>0)
{
struct Node Next = frontier.top();
visited.push_back(Next.config);
frontier.pop();
if(Next.depth < Current_Max_Depth)
{
int pos_of_hole = Find_Position_of_Hole(Next.config);
if(pos_of_hole==0)
{
std::vector<int> Down_Child = Move_Down(Next.config);
struct Node Down_Node = {Down_Child,Next.depth+1,1,&Next}; //****
if(!(std::find(visited.begin(), visited.end(), Down_Child)!=visited.end()))
{
if(Goal_Test(Down_Child))
{
goal_node = Down_Node;
goal_reached = true;
break;
}
frontier.push(Down_Node);
}
std::vector<int> Right_Child = Move_Right(Next.config);
struct Node Right_Node = {Right_Child,Next.depth+1,3,&Next}; //*******Passing next by reference here is not working since Next is always at the same data location. The nodes one layer up from the leaf nodes end up all pointing to themselves.
if(!(std::find(visited.begin(), visited.end(), Right_Child)!=visited.end()))
{
if(Goal_Test(Right_Child))
{
goal_node = Right_Node;
goal_reached = true;
break;
}
frontier.push(Right_Node);
}
}
if(pos_of_hole==1)
... does very similar for pos 1 through 8, not related to bug ...
} //End of if(Next.Depth < Max_Depth)
} //End of while(frontier.size()>0)
if(goal_reached)
{
break;
}
Current_Max_Depth++;
}
struct Node initial = {orig_config, 0, 0, NULL};
Creates a Node on the stack. When you create the next child
struct Node Down_Node = {Down_Child,Next.depth+1,1,&Next};
You are taking the address of that local stack object. When the loop ends Next is destroyed and then it is constructed again at the beginning of the next iteration of the while loop. If the nodes need to persist then you need to allocate them with new and then delete then when you are done.
On a side note the struct keyword is not required on variable declarations in C++. See Why does C need “struct” keyword and not C++? for more information.

Binary Search tree Array implementation C++

I am in the process of implementing a Binary Search tree that gets represented using the Array implementation. This is my code so far: Take note that I have done with the Structure of tree and it is being saved as a Linked List. I want to convert this linked list into an array.
My thoughts on how to go about this are as followed. Make a return_array function. Have the Size of the array set to the Max number of nodes( 2^(n-1)+1) and go through the linked list. Root node would be # position 0 on the array then his L-child = (2*[index_of_parent]+1) and R-child = (2*[index_of_parent]+2). I looked around for a bit and searched to find something that can get me an idea of how I can keep track of each node and how I can go through each one.
Am I overthinking this problem?
Can there be a Recursion?
Also, I'm considering creating a visual tree instead of an array but have no idea how to space it out correctly. If anyone has an idea on how to do that it would be awesome to get a better understanding of that.
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <cmath>
using namespace std;
struct node {
int data;
struct node* left;
struct node* right;
};
void inorder(struct node* node){
if(node){
inorder(node->left);
cout << node->data << " ";
inorder(node->right);
}
}
void insert(struct node** node, int key){
if(*node == NULL){
(*node) = (struct node*)malloc(sizeof(struct node));
(*node)->data = key;
(*node)->left = NULL;
(*node)->right = NULL;
printf("inserted node with data %d\n", (*node)->data);
}
else if ((*node)->data > key){
insert((&(*node)->left),key);
}
else
insert((&(*node)->right),key);
}
int max_tree(struct node* node){
int left,right;
if(node == NULL)
return 0;
else
{
left=max_tree(node->left);
right=max_tree(node->right);
if(left>right)
return left+1;
else
return right+1;
}
}
//This is where i dont know how to keep the parent/children the array.
void return_array(struct node* node, int height){
int max;
height = height - 1;
max = pow(2, height) - 1;
int arr [height];
}
int main(){
int h;
struct node* root = NULL;
insert(&root, 10);
insert(&root, 20);
insert(&root, 5);
insert(&root, 2);
inorder(root);
cout << endl;
cout << "Height is: ";
cout << max_tree(root);
h = max_tree(root)
return_array(root, h)
}
Considering that you want to efficiently store a binary search tree, using
l = 2i + 1
r = 2i + 2
will waste space every time your tree encounters a leaf node that is not occurring at the end of the tree (breadth-first). Consider the following simple example:
2
/ \
1 4
/ \
3 5
This (when transformed breadth-first into an array) results in
[ 2, 1, 4, -, -, 3, 5 ]
And wastes two slots in the array.
Now if you want to store the same tree in an array without wasting space, just transform it into an array depth-first:
[ 2 1 4 3 5 ]
To recover the original tree from this, follow these steps for each node:
Choose the first node as root
For each node (including root), choose
a) the left child as the next smaller key from the array after the current key
b) the right child as the next bigger key from the array, being no larger than the smallest parent key encountered when last branching left, and smaller than the direct parent's key when you are currently in it's left branch
Obviously finding the correct b) is slightly more complex, but not too much. Refer to my code example here.
If I'm not mistaken, transforming to and from an array will take O(n) in either case. And as no space is wasted, space complexity is also O(n).
This works because binary search trees have more structure than ordinary binary trees; here, I'm just using the binary search tree property of the left child being smaller, and the right child being larger than the current node's key.
EDIT:
After doing some further research on the topic, I found that reconstructing the tree in preorder traversal order is much simpler. The recursive function doing that is implemented here and here, respectively.
It basically consists of these steps:
As long as the input array has unseen entries,
If the value to insert is greater than the current branch's minimum value and less than the current branch's maximum allowed,
Add a node to the tree at the current position and set it's value to the current input value
Remove current value from input
If there are items left in the input,
Recurse into the left child
Recurse into the right child
The current minimum and maximum values are defined by the position inside the tree (left child: less than parent, right child: greater than parent).
For more elaborate details, please refer to my source code links.
If you want to store the tree node in a array,you had better to start from 1 position of your array!So the relation between the parent and its children should be simple:
parent = n;
left = 2n;
right = 2n + 1;
you should BFS the tree,and store the node in the array(If the node is null you should also store in the array using a flag ex 0),you should get the very array of the tree!
To do this you have to follow these steps.
Create an empty queue.
Make the first node of the list as root, and enqueue it to the queue.
Until we reach the end of the list, do the following.
a. Dequeue one node from the queue. This is the current parent.
b. Traverse two nodes in the list, add them as children of the current parent.
c. Enqueue the two nodes into the queue.
Time Complexity: Time complexity of the above solution is O(n) where n is the number of nodes.

BFS implementation

i was recently solving a bfs problem where each node is a different arrangement of elements of an array. but i was unable to come up with a suitable data structure to keep track of the visited nodes in the expanded tree. generally the nodes are different strings so we can just use a map to mark a node as visited but what DS should i use in the above case?
Consider the following pseudocode:
type Node; // information pertaining to a node
type Path; // an ordered list of nodes
type Area; // an area containing linked neighboring nodes
type Queue; // a FIFO queue structure
function Traverse(Area a, Node start, Node end) returns Path:
Queue q;
Node n;
// traverse backwards, from finish to start
q.push(end); // add initial node to queue
end.parent = end; // set first node's parent to itself
while (not q.empty()):
n = q.pop(); // remove first element
if (n == start) // if element is the final element, we're done
break;
for (Node neighbor in a.neighbors(n)): // for each neighboring node
if (neighbor.parent != Null): // if already visited, skip
continue;
neighbor.parent = n; // otherwise, visit
q.push(neighbor); // then add to queue
Path p; // prepare to build path from visited list
for (Node previous = Null, current = n;
previous != current;
previous = current, current = current.parent):
p.add(current); // for each node from start to end, add node to p
// Note that the first node's parent is itself
// thus dissatisfying the loop condition
return p;
The "visited list" is stored as the node's parent. Coding this to C++, you would probably handle most of the nodes as references or pointers since this pseudocode relies on referential behavior.
You start with an Area, which is a field of Nodes. The area knows where each node is in relation to the others. You start at one specific Node, the "start" node, and push it into a queue.
Traversing the area is as simple as getting the list of neighboring nodes from the Area, skipping them if they're already visited, and setting their parent and adding them to the queue otherwise. Traversal ends when a node removed from the queue equals the destination node. You could speed up the algorithm a little by doing this check during the neighbor loop, when the node is initially encountered.
NOTE: You do not need to generate every possible node within the area before beginning the traversal, the Area requires only that once it has created a node, it keeps track of it. This might help your situation where it appears you use permutations of strings or arrays: you could push the starting and ending nodes into the Area, and it could generate and cache neighbor nodes on the fly. You might store them as vectors, which can be compared for equality based on their order and contents with the == operator. See this example.
The traversal goes backwards rather than forwards because it makes rebuilding the path easier (rather than ending up at the end node, with each parent the node before it, you end up at the start node, with each parent the node after it)
Data Structure Summary
Node would need to keep track of enough information for Area to identify it uniquely (via an array index or a name or something), as well as a parent node. The parent nodes should be set to NULL before the traversal to avoid weird behavior, since traversal will ignore any node with its parent set. This keeps track of the visited state too: visited is equivalent to (parent != NULL). Doing it this way also keeps you from having to keep track of the entire path in the queue, which would be very computationally intensive.
Area needs to maintain a list of Node, and needs a neighbor map, or a mapping of which nodes neighbor which other nodes. It's possible that this mapping could be generated on the fly with a function rather than being looked up from a table or some more typical approach. It should be able to provide the neighbors of a node to a caller. It might help to have a helper method that clears the parents of every node as well.
Path is basically a list type, containing an ordered list of nodes.
Queue is whatever FIFO queue is available. You could do it with a linked list.
I like how the syntax highlighting worked on my Wuggythovasp++.
At least as a start, you could try using/implementing something like Java's Arrays.toString() and using a map. Each arrangement would result in a different string, and thus it'll at least get somewhere.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author VAISAKH N
*/
public class BFSME {
public static String path = "";
public static String add = "";
public static void findrec(String temp, String end, String[][] m, int j) {
if (temp.equals(m[j][1])) {
add = m[j][0] + temp + end + "/";
end = temp + end;
System.out.println(end);
path = path + add;
temp = "" + add.charAt(0);
System.out.println("Temp" + temp);
for (int k = 0; k < m.length; k++) {
findrec(temp, end, m, k);
}
}
}
public static void main(String[] args) {
String[][] data = new String[][]{{"a", "b"}, {"b", "c"}, {"b", "d"}, {"a", "d"}};
String[][] m = new String[data.length][2];
for (int i = 0; i < data.length; i++) {
String temp = data[i][0];
String end = data[i][1];
m[i][0] = temp;
m[i][1] = end;
path = path + temp + end + "/";
for (int j = 0; j < m.length; j++) {
findrec(temp, end, m, j);
}
}
System.out.println(path);
}
}
Just for the purpose of understanding, i have provided my sample code here (its in C#)
private void Breadth_First_Travers(Node node)
{
// First Initialize a queue -
// it's retrieval mechanism works as FIFO - (First in First Out)
Queue<Node> myQueue = new Queue<Node>();
// Add the root node of your graph into the Queue
myQueue.Enqueue(node);
// Now iterate through the queue till it is empty
while (myQueue.Count != 0)
{
// now, retrieve the first element from the queue
Node item = myQueue.Dequeue();
Console.WriteLine("item is " + item.data);
// Check if it has any left child
if (item.left != null)
{
// If left child found - Insert/Enqueue into the Queue
myQueue.Enqueue(item.left);
}
// Check if it has right child
if (item.right != null)
{
// If right child found Insert/Enqueue into the Queue
myQueue.Enqueue(item.right);
}
// repeat the process till the Queue is empty
}
}
Here sample code is give with reference of http://en.wikipedia.org/wiki/Binary_tree
as tree is a type of graph it self.
Here is BFS implementation using C++ STL(adjacency lists) for Graph. Here three Array and a Queue is used for complete implementation.
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
//Adding node pair of a Edge in Undirected Graph
void addEdge( vector<int> adj[], int u, int v){
adj[u].push_back(v); // 1st push_back
adj[v].push_back(u); //2nd push_back
//for Directed Graph use only one push_back i.e., 1st push_back() rest is same
}
//Traversing through Graph from Node 0 in Adjacency lists way
void showGraph( vector<int>adj[], int size){
cout<<"Graph:\n";
for(int i=0; i<size ; i++){
cout<<i;
for( vector<int>::iterator itr= adj[i].begin() ; itr!=adj[i].end(); itr++){
cout<<" -> "<<*itr;
}
cout<<endl;
}
}
//Prints Array elements
void showArray(int A[]){
for(int i=0; i< 6; i++){
cout<<A[i]<<" ";
}
}
void BFS( vector<int>adj[], int sNode, int N){
// Initialization
list<int>queue; //Queue declaration
int color[N]; //1:White, 2:Grey, 3:Black
int parentNode[N]; //Stores the Parent node of that node while traversing, so that you can reach to parent from child using this
int distLevel[N]; //stores the no. of edges required to reach the node,gives the length of path
//Initialization
for(int i=0; i<N; i++){
color[i] = 1; //Setting all nodes as white(1) unvisited
parentNode[i] = -1; //setting parent node as null(-1)
distLevel[i] = 0; //initializing dist as 0
}
color[sNode] = 2; //since start node is visited 1st so its color is grey(2)
parentNode[sNode] = -1; //parent node of start node is null(-1)
distLevel[sNode] = 0; //distance is 0 since its a start node
queue.push_back(sNode); //pushing start node(sNode) is queue
// Loops runs till Queue is not empty if queue is empty all nodes are visited
while( !queue.empty()){
int v = queue.front(); //storing queue's front(Node) to v
// queue.pop_front();//Dequeue poping element from queue
//Visiting all nodes connected with v-node in adjacency list
for(int i=0; i<adj[v].size() ;i++){
if( color[ adj[v][i] ] == 1){// if node is not visited, color[node]==1 which is white
queue.push_back(adj[v][i]); //pushing that node to queue
color[adj[v][i]]=2; //setting as grey(2)
parentNode[ adj[v][i] ] = v; //parent node is stored distLevel[ adj[v][i] ] = distLevel[v]+1; //level(dist) is incremented y from dist(parentNode)
}
}//end of for
color[v]=3;
queue.pop_front();//Dequeue
}
printf("\nColor: \n");showArray(color);
printf("\nDistLevel:\n");showArray(distLevel);
printf("\nParentNode:\n");showArray(parentNode);
}
int main(){
int N,E,u,v;//no of nodes, No of Edges, Node pair for edge
cout<<"Enter no of nodes"<<endl;
cin>>N;
vector<int> adj[N]; //vector adjacency lists
cout<<"No. of edges"<<endl;
cin>>E;
cout<<"Enter the node pair for edges\n";
for( int i=0; i<E;i++){
cin>>u>>v;
addEdge(adj, u, v); //invoking addEdge function
}
showGraph(adj,N); //Printing Graph in Adjacency list format
BFS(adj,0,N); /invoking BFS Traversal
}