top of page

Daily Coding Problem #12

Writer's picture: Mischievous_FaceMischievous_Face

#include <iostream>

#include <string>

#include <vector>

#include <queue>


using namespace std;


class Node

{

public:

int value;

Node* left = nullptr;

Node* right = nullptr;

Node* parent = nullptr;


Node(int newValue, Node* nodeParent = nullptr)

{

value = newValue;

parent = nodeParent;

}

};


// Print the nodes in a binary tree level - wise.For example, the following should print 1, 2, 3, 4, 5.

//

// 1

// / \

// 2 3

// / \

// 4 5

void printLevelOrder(Node* root)

{

if (root == NULL)

return;


vector<int> nodes2print;

int currentLevel = 0;

int minLevel = 1;

int minSum = root->value;


queue<Node*> q;

q.push(root);


// use a queue to traverse each level of the tree

while (!q.empty())

{

// get queue size when the order traversal is finished

int count = q.size();


while (count--)

{

Node *temp = q.front();

q.pop();


// print the current node

cout << temp->value << ", ";


// enqueue both children of the current node

if (temp->left != NULL)

q.push(temp->left);


if (temp->right != NULL)

q.push(temp->right);

}

}


for (unsigned i = 0; i < nodes2print.size(); ++i)

{

cout << nodes2print[i] << endl;

}

}


Node* generateTree()

{

Node* head = new Node(1);

head->left = new Node(2, head);

head->right = new Node(3, head);

head->right->left = new Node(4, head->right);

head->right->right = new Node(5, head->right);


cout << "Tree constructed" << endl;


return head;

}


int main()

{

Node* tree = generateTree();

printLevelOrder(tree);


return 0;

}

3 views0 comments

Recent Posts

See All

Comments


© 2020 Josh Painter

bottom of page