Skip to content

Commit

Permalink
Merge pull request #595 from Rajat-dey/patch-6
Browse files Browse the repository at this point in the history
Create Print_nodes_odd_level_tree.cpp
  • Loading branch information
Srikant Singh authored Oct 27, 2018
2 parents 9e0aef6 + fc57ad0 commit 8bb1331
Showing 1 changed file with 71 additions and 0 deletions.
71 changes: 71 additions & 0 deletions Data Structures/Binary Tree/Print_nodes_odd_level_tree.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@

#include <bits/stdc++.h>
using namespace std;

struct Node {
int data;
Node* left, *right;
};

// Iterative method to do level order traversal line by line
void printOddNodes(Node *root)
{
// Base Case
if (root == NULL) return;

// Create an empty queue for level
// order tarversal
queue<Node *> q;

// Enqueue root and initialize level as odd
q.push(root);
bool isOdd = true;

while (1)
{
// nodeCount (queue size) indicates
// number of nodes at current level.
int nodeCount = q.size();
if (nodeCount == 0)
break;

// Dequeue all nodes of current level
// and Enqueue all nodes of next level
while (nodeCount > 0)
{
Node *node = q.front();
if (isOdd)
cout << node->data << " ";
q.pop();
if (node->left != NULL)
q.push(node->left);
if (node->right != NULL)
q.push(node->right);
nodeCount--;
}

isOdd = !isOdd;
}
}

// Utility method to create a node
struct Node* newNode(int data)
{
struct Node* node = new Node;
node->data = data;
node->left = node->right = NULL;
return (node);
}

// Driver code
int main()
{
struct Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
printOddNodes(root);

return 0;
}

0 comments on commit 8bb1331

Please sign in to comment.