You are on page 1of 20

LEVEL ORDER

Calculate height of binary tree | Iterative & Recursive - Techie Delight


int height(Node *root)
{
// empty tree has height 0
if (root == nullptr)
return 0;

// create an empty queue and enqueue root node


list<Node*> queue;
queue.push_back(root);

Node* front = nullptr;


int height = 0;

// run till queue is not empty


while (!queue.empty())
{
// calculate number of nodes in current level
int size = queue.size();

// process every node of current level and enqueue their


// non-empty left and right child to queue
while (size--)
{
front = queue.front();
queue.pop_front();

if (front->left)
queue.push_back(front->left);

if (front->right)
queue.push_back(front->right);
}

// increment height by 1 for each level


height++;
}

return height;
}
Delete given Binary Tree | Iterative & Recursive - Techie Delight
void deleteBinaryTree(Node* &root)
{
// empty tree
if (root == nullptr)
return;

// create an empty queue and enqueue root node


queue<Node*> queue;
queue.push(root);

Node *front = nullptr;


// run till queue is not empty
while (!queue.empty())
{
// delete each node in the queue one by one after pushing their
// non-empty left and right child to the queue
front = queue.front();
queue.pop();

if (front->left)
queue.push(front->left);

if (front->right)
queue.push(front->right);

// Important - delete front node ONLY after enqueuing its children


delete front;
}

// set root as NULL before returning


root = nullptr;
}
Check if given binary tree is complete binary tree or not - Techie Delight
bool isComplete(Node* root)
{
// return if tree is empty
if (root == nullptr)
return false;

// create an empty queue and enqueue root node


list<Node*> queue;
queue.push_back(root);

// pointer to store current node


Node* front = nullptr;

// flag to mark end of full nodes


bool flag = false;

// run till queue is not empty


while (queue.size())
{
// pop front node from the queue
front = queue.front();
queue.pop_front();

// if we have encountered a non-full node before and current node


// is not a leaf, tree cannot be complete tree
if (flag && (front->left || front->right))
return false;

// if left child is empty and right child exists, binary


// tree cannot be complete
if (front->left == nullptr && front->right)
return false;

// if left child exists, enqueue it


if (front->left)
queue.push_back(front->left);

// if current node is a non-full node, set flag to true


else
flag = true;

// if right child exists, enqueue it


if (front->right)
queue.push_back(front->right);

// if current node is a non-full node, set flag to true


else
flag = true;
}

return true;
}
Invert given Binary Tree | Recursive and Iterative solution - Techie Delight
void invertBinaryTree(Node* root)
{
// base case: if tree is empty
if (root == nullptr)
return;

// maintain a queue and push push root node


queue<Node*> q;
q.push(root);

// run till queue is not empty


while (!q.empty())
{
// pop top node from queue
Node* curr = q.front();
q.pop();

// swap left child with right child


swap(curr->left, curr->right);

// push left child of popped node to the queue


if (curr->left)
q.push(curr->left);

// push right child of popped node to the queue


if (curr->right)
q.push(curr->right);
}
}
Print corner nodes of every level in binary tree - Techie Delight
void print(Node *root)
{
// return if tree is empty
if (root == nullptr)
return;

// create an empty queue to store Tree nodes


queue<Node*> q;

// enqueue root node


q.push(root);

// run till queue is not empty


while (!q.empty())
{
// get size of current level
int size = q.size();
int n = size;

// process all nodes present in current level


while (n--)
{
Node *node = q.front();
q.pop();

// if corner node found, print it


if (n == size - 1 || n == 0)
cout << node->data << " ";

// enqueue left and right child of current node


if (node->left != nullptr)
q.push(node->left);

if (node->right != nullptr)
q.push(node->right);
}

// terminate the level by printing newline


cout << endl;
}
}
Print level order traversal line by line | Set 1 - GeeksforGeeks
http://www.geeksforgeeks.org/print-level-order-traversal-line-line/

void printLevelOrder(node *root)


{
// Base Case
if (root == NULL) return;

// Create an empty queue for level order tarversal


queue<node *> q;

// Enqueue Root and initialize height


q.push(root);

while (1)
{
// nodeCount (queue size) indicates number of nodes
// at current lelvel.
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();
cout << node->data << " ";
q.pop();
if (node->left != NULL)
q.push(node->left);
if (node->right != NULL)
q.push(node->right);
nodeCount--;
}
cout << endl;
}
}

Maximum width of a binary tree - GeeksforGeeks


http://www.geeksforgeeks.org/maximum-width-of-a-binary-tree/

int maxWidth(struct Node * root)


{
// Base case
if (root == NULL)
return 0;

// Initialize result
int result = 0;

// Do Level order traversal keeping track of number


// of nodes at every level.
queue<Node*> q;
q.push(root);
while (!q.empty())
{
// Get the size of queue when the level order
// traversal for one level finishes
int count = q.size() ;

// Update the maximum node count value


result = max(count, result);

// Iterate for all the nodes in the queue currently


while (count--)
{
// Dequeue an node from queue
Node *temp = q.front();
q.pop();

// Enqueue left and right children of


// dequeued node
if (temp->left != NULL)
q.push(temp->left);
if (temp->right != NULL)
q.push(temp->right);
}
}

return result;
}

Connect nodes at same level - GeeksforGeeks


http://www.geeksforgeeks.org/connect-nodes-at-same-level/

Method 1 (Extend Level Order Traversal or BFS)


Consider the method 2 of Level Order Traversal. The method 2 can easily be extended to
connect nodes of same level. We can augment queue entries to contain level of nodes also which
is 0 for root, 1 for roots children and so on. So a queue node will now contain a pointer to a tree
node and an integer level. When we enqueue a node, we make sure that correct level value for
node is being set in queue. To set nextRight, for every node N, we dequeue the next node from
queue, if the level number of next node is same, we set the nextRight of N as address of the
dequeued node, otherwise we set nextRight of N as NULL.

Time Complexity: O(n)

Check whether a given Binary Tree is Complete or not | Set 1 (Iterative Solution) -
GeeksforGeeks
http://www.geeksforgeeks.org/check-if-a-given-binary-tree-is-complete-tree-or-not/
bool isCompleteBT(struct node* root)
{
// Base Case: An empty tree is complete Binary Tree
if (root == NULL)
return true;

// Create an empty queue


int rear, front;
struct node **queue = createQueue(&front, &rear);

// Create a flag variable which will be set true


// when a non full node is seen
bool flag = false;

// Do level order traversal using queue.


enQueue(queue, &rear, root);
while(!isQueueEmpty(&front, &rear))
{
struct node *temp_node = deQueue(queue, &front);

/* Check if left child is present*/


if(temp_node->left)
{
// If we have seen a non full node, and we see a node
// with non-empty left child, then the given tree is not
// a complete Binary Tree
if (flag == true)
return false;

enQueue(queue, &rear, temp_node->left); // Enqueue Left Child


}
else // If this a non-full node, set the flag as true
flag = true;

/* Check if right child is present*/


if(temp_node->right)
{
// If we have seen a non full node, and we see a node
// with non-empty right child, then the given tree is not
// a complete Binary Tree
if(flag == true)
return false;

enQueue(queue, &rear, temp_node->right); // Enqueue Right Child


}
else // If this a non-full node, set the flag as true
flag = true;
}

// If we reach here, then the tree is complete Bianry Tree


return true;
}

Linked complete binary tree & its creation - GeeksforGeeks


http://www.geeksforgeeks.org/linked-complete-binary-tree-its-creation/

void insert(struct node **root, int data, struct Queue* queue)


{
// Create a new node for given data
struct node *temp = newNode(data);

// If the tree is empty, initialize the root with new node.


if (!*root)
*root = temp;

else
{
// get the front node of the queue.
struct node* front = getFront(queue);

// If the left child of this front node doesnt exist, set the
// left child as the new node
if (!front->left)
front->left = temp;

// If the right child of this front node doesnt exist, set the
// right child as the new node
else if (!front->right)
front->right = temp;

// If the front node has both the left child and right child,
// Dequeue() it.
if (hasBothChild(front))
Dequeue(queue);
}

// Enqueue() the new node for later insertions


Enqueue(temp, queue);
}

Reverse Level Order Traversal - GeeksforGeeks


http://www.geeksforgeeks.org/reverse-level-order-traversal/
void reverseLevelOrder(node* root)
{
stack <node *> S;
queue <node *> Q;
Q.push(root);

// Do something like normal level order traversal order. Following are the
// differences with normal level order traversal
// 1) Instead of printing a node, we push the node to stack
// 2) Right subtree is visited before left subtree
while (Q.empty() == false)
{
/* Dequeue node and make it root */
root = Q.front();
Q.pop();
S.push(root);

/* Enqueue right child */


if (root->right)
Q.push(root->right); // NOTE: RIGHT CHILD IS ENQUEUED BEFORE LEFT

/* Enqueue left child */


if (root->left)
Q.push(root->left);
}

// Now pop all items from stack one by one and print them
while (S.empty() == false)
{
root = S.top();
cout << root->data << " ";
S.pop();
}
}

Find next right node of a given key - GeeksforGeeks


http://www.geeksforgeeks.org/find-next-right-node-of-a-given-key/

node* nextRight(node *root, int k)


{
// Base Case
if (root == NULL)
return 0;

// Create an empty queue for level order tarversal


queue<node *> qn; // A queue to store node addresses
queue<int> ql; // Another queue to store node levels

int level = 0; // Initialize level as 0

// Enqueue Root and its level


qn.push(root);
ql.push(level);

// A standard BFS loop


while (qn.size())
{
// dequeue an node from qn and its level from ql
node *node = qn.front();
level = ql.front();
qn.pop();
ql.pop();

// If the dequeued node has the given key k


if (node->key == k)
{
// If there are no more items in queue or given node is
// the rightmost node of its level, then return NULL
if (ql.size() == 0 || ql.front() != level)
return NULL;

// Otherwise return next node from queue of nodes


return qn.front();
}

// Standard BFS steps: enqueue children of this node


if (node->left != NULL)
{
qn.push(node->left);
ql.push(level+1);
}
if (node->right != NULL)
{
qn.push(node->right);
ql.push(level+1);
}
}

// We reach here if given key x doesn't exist in tree


return NULL;
}
Print nodes between two given level numbers of a binary tree - GeeksforGeeks
http://www.geeksforgeeks.org/given-binary-tree-print-nodes-two-given-level-numbers/

void printLevels(Node* root, int low, int high)


{
queue <Node *> Q;

Node *marker = new Node; // Marker node to indicate end of level

int level = 1; // Initialize level number

// Enqueue the only first level node and marker node for end of level
Q.push(root);
Q.push(marker);

// Simple level order traversal loop


while (Q.empty() == false)
{
// Remove the front item from queue
Node *n = Q.front();
Q.pop();

// Check if end of level is reached


if (n == marker)
{
// print a new line and increment level number
cout << endl;
level++;

// Check if marker node was last node in queue or


// level number is beyond the given upper limit
if (Q.empty() == true || level > high) break;

// Enqueue the marker for end of next level


Q.push(marker);

// If this is marker, then we don't need print it


// and enqueue its children
continue;
}

// If level is equal to or greater than given lower level,


// print it
if (level >= low)
cout << n->key << " ";
// Enqueue children of non-marker node
if (n->left != NULL) Q.push(n->left);
if (n->right != NULL) Q.push(n->right);
}
}

Perfect Binary Tree Specific Level Order Traversal - GeeksforGeeks


http://www.geeksforgeeks.org/perfect-binary-tree-specific-level-order-traversal/

void printSpecificLevelOrder(Node *root)


{
if (root == NULL)
return;

// Let us print root and next level first


cout << root->data;

// / Since it is perfect Binary Tree, right is not checked


if (root->left != NULL)
cout << " " << root->left->data << " " << root->right->data;

// Do anything more if there are nodes at next level in


// given perfect Binary Tree
if (root->left->left == NULL)
return;

// Create a queue and enqueue left and right children of root


queue <Node *> q;
q.push(root->left);
q.push(root->right);

// We process two nodes at a time, so we need two variables


// to store two front items of queue
Node *first = NULL, *second = NULL;

// traversal loop
while (!q.empty())
{
// Pop two items from queue
first = q.front();
q.pop();
second = q.front();
q.pop();

// Print children of first and second in reverse order


cout << " " << first->left->data << " " << second->right->data;
cout << " " << first->right->data << " " << second->left->data;

// If first and second have grandchildren, enqueue them


// in reverse order
if (first->left->left != NULL)
{
q.push(first->left);
q.push(second->right);
q.push(first->right);
q.push(second->left);
}
}
}

Find multiplication of sums of data of leaves at same levels - GeeksforGeeks


http://www.geeksforgeeks.org/find-multiplication-of-sums-of-data-of-all-leaves-at-sane-levels/

/* Calculate sum of all leaf Nodes at each level and returns


multiplication of sums */
int sumAndMultiplyLevelData(Node *root)
{
// Tree is empty
if (!root)
return 0;

int mul = 1; /* To store result */

// Create an empty queue for level order tarversal


queue<Node *> q;

// Enqueue Root and initialize height


q.push(root);

// Do level order traversal of tree


while (1)
{
// NodeCount (queue size) indicates number of Nodes
// at current lelvel.
int NodeCount = q.size();

// If there are no Nodes at current level, we are done


if (NodeCount == 0)
break;

// Initialize leaf sum for current level


int levelSum = 0;
// A boolean variable to indicate if found a leaf
// Node at current level or not
bool leafFound = false;

// Dequeue all Nodes of current level and Enqueue all


// Nodes of next level
while (NodeCount > 0)
{
// Process next Node of current level
Node *Node = q.front();

/* if Node is a leaf, update sum at the level */


if (isLeaf(Node))
{
leafFound = true;
levelSum += Node->data;
}
q.pop();

// Add children of Node


if (Node->left != NULL)
q.push(Node->left);
if (Node->right != NULL)
q.push(Node->right);
NodeCount--;
}

// If we found at least one leaf, we multiply


// result with level sum.
if (leafFound)
mul *= levelSum;
}

return mul; // Return result


}

Find Minimum Depth of a Binary Tree - GeeksforGeeks


http://www.geeksforgeeks.org/find-minimum-depth-of-a-binary-tree/

// Iterative method to find minimum depth of Bianry Tree


int minDepth(Node *root)
{
// Corner Case
if (root == NULL)
return 0;
// Create an empty queue for level order tarversal
queue<qItem> q;

// Enqueue Root and initialize depth as 1


qItem qi = {root, 1};
q.push(qi);

// Do level order traversal


while (q.empty() == false)
{
// Remove the front queue item
qi = q.front();
q.pop();

// Get details of the remove item


Node *node = qi.node;
int depth = qi.depth;

// If this is the first leaf node seen so far


// Then return its depth as answer
if (node->left == NULL && node->right == NULL)
return depth;

// If left subtree is not NULL, add it to queue


if (node->left != NULL)
{
qi.node = node->left;
qi.depth = depth + 1;
q.push(qi);
}

// If right subtree is not NULL, add it to queue


if (node->right != NULL)
{
qi.node = node->right;
qi.depth = depth+1;
q.push(qi);
}
}
return 0;
}

Print extreme nodes of each level of Binary Tree in alternate order - GeeksforGeeks
http://www.geeksforgeeks.org/print-extreme-nodes-of-each-level-of-binary-tree-in-alternate-
order/
/* Function to print nodes of extreme corners
of each level in alternate order */
void printExtremeNodes(Node* root)
{
if (root == NULL)
return;

// Create a queue and enqueue left and right


// children of root
queue<Node*> q;
q.push(root);

// flag to indicate whether leftmost node or


// the rightmost node has to be printed
bool flag = false;
while (!q.empty())
{
// nodeCount indicates number of nodes
// at current level.
int nodeCount = q.size();
int n = nodeCount;

// Dequeue all nodes of current level


// and Enqueue all nodes of next level
while (n--)
{
Node* curr = q.front();

// Enqueue left child


if (curr->left)
q.push(curr->left);

// Enqueue right child


if (curr->right)
q.push(curr->right);

// Dequeue node
q.pop();

// if flag is true, print leftmost node


if (flag && n == nodeCount - 1)
cout << curr->data << " ";

// if flag is false, print rightmost node


if (!flag && n == 0)
cout << curr->data << " ";
}
// invert flag for next level
flag = !flag;
}
}

Convert a Binary Tree into Doubly Linked List in spiral fashion - GeeksforGeeks
http://www.geeksforgeeks.org/convert-a-binary-tree-into-doubly-linked-list-in-spiral-fashion/

void spiralLevelOrder(Node *root)


{
// Base Case
if (root == NULL)
return;

// Create an empty deque for doing spiral


// level order traversal and enqueue root
deque<Node*> q;
q.push_front(root);

// create a stack to store Binary Tree nodes


// to insert into DLL later
stack<Node*> stk;

int level = 0;
while (!q.empty())
{
// nodeCount indicates number of Nodes
// at current level.
int nodeCount = q.size();

// Dequeue all Nodes of current level and


// Enqueue all Nodes of next level
if (level&1) //odd level
{
while (nodeCount > 0)
{
// dequeue node from front & push it to
// stack
Node *node = q.front();
q.pop_front();
stk.push(node);

// insert its left and right children


// in the back of the deque
if (node->left != NULL)
q.push_back(node->left);
if (node->right != NULL)
q.push_back(node->right);

nodeCount--;
}
}
else //even level
{
while (nodeCount > 0)
{
// dequeue node from the back & push it
// to stack
Node *node = q.back();
q.pop_back();
stk.push(node);

// inserts its right and left children


// in the front of the deque
if (node->right != NULL)
q.push_front(node->right);
if (node->left != NULL)
q.push_front(node->left);
nodeCount--;
}
}
level++;
}

// head pointer for DLL


Node* head = NULL;

// pop all nodes from stack and


// push them in the beginning of the list
while (!stk.empty())
{
push(&head, stk.top());
stk.pop();
}

cout << "Created DLL is:\n";


printList(head);
}

Find next node in same level for given node in a binary tree - Techie Delight
http://www.techiedelight.com/find-next-node-in-same-level-binary-tree/
Find next node in same level for given node

Node* findRightNode(Node* root, int val)


{
// return null if tree is empty
if (root == nullptr)
return nullptr;

// create an empty queue and enqueue root node


list<Node*> queue;
queue.push_back(root);

// pointer to store current node


Node* front = nullptr;

// run till queue is not empty


while (!queue.empty())
{
// calculate number of nodes in current level
int size = queue.size();

// process every node of current level and enqueue their


// non-empty left and right child to queue
while (size--)
{
front = queue.front();
queue.pop_front();

// if desired node is found, return its next right node


if (front->key == val)
{
// if next right node doesn't exists, return null
if (queue.empty())
return nullptr;
return queue.front();
}

if (front->left)
queue.push_back(front->left);

if (front->right)
queue.push_back(front->right);
}
}
return nullptr;
}

Print left view of binary tree - Techie Delight


void leftView(Node* root)
{
// return if tree is empty
if (root == nullptr)
return;

// create an empty queue and enqueue root node


list<Node*> queue;
queue.push_back(root);

// pointer to store current node


Node* curr = nullptr;

// run till queue is not empty


while (!queue.empty())
{
// calculate number of nodes in current level
int size = queue.size();
int i = 0;

// process every node of current level and enqueue their


// non-empty left and right child to queue
while (i++ < size)
{
curr = queue.front();
queue.pop_front();

// if this is first node of current level, print it


if (i == 1)
cout << curr->key << " ";

if (curr->left)
queue.push_back(curr->left);

if (curr->right)
queue.push_back(curr->right);
}
}
}

You might also like