xxxxxxxxxx
// Recursive CPP program for level
// order traversal of Binary 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, *right;
};
/* Function prototypes */
void printCurrentLevel(node* root, int level);
int height(node* node);
node* newNode(int data);
/* Function to print level
order traversal a tree*/
void printLevelOrder(node* root)
{
int h = height(root);
int i;
for (i = 1; i <= h; i++)
printCurrentLevel(root, i);
}
/* Print nodes at a current level */
void printCurrentLevel(node* root, int level)
{
if (root == NULL)
return;
if (level == 1)
cout << root->data << " ";
else if (level > 1) {
printCurrentLevel(root->left, level - 1);
printCurrentLevel(root->right, level - 1);
}
}
/* Compute the "height" of a tree -- the number of
nodes along the longest path from the root node
down to the farthest leaf node.*/
int height(node* node)
{
if (node == NULL)
return 0;
else {
/* compute the height of each subtree */
int lheight = height(node->left);
int rheight = height(node->right);
/* use the larger one */
if (lheight > rheight) {
return (lheight + 1);
}
else {
return (rheight + 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 << "Level Order traversal of binary tree is \n";
printLevelOrder(root);
return 0;
}
// This code is contributed by rathbhupendra
xxxxxxxxxx
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> list = new ArrayList<>();
Deque<TreeNode> queue = new ArrayDeque<>();
if(root==null)
return list;
queue.offerLast(root);
while(!queue.isEmpty())
{
ArrayList<Integer> l= new ArrayList<>();
int size=queue.size();
for(int i=0;i<size;i++)
{
TreeNode node=queue.pollFirst();
if(node.left!=null)
queue.offerLast(node.left);
if(node.right!=null)
queue.offerLast(node.right);
l.add(node.val);
}
list.add(l);
}
return list;
}
}
xxxxxxxxxx
/*
node class contains:
node* left;
node* right;
int value;
*/
void levelOrder(node* root){
node* ptr=nullptr;
queue<node*> q;
q.push(root);
while(!q.empty()){
ptr=q.front();
cout<<ptr->value<<endl;
if(ptr->left!=nullptr){
q.push(ptr->left);
}
if(ptr->right!=nullptr){
q.push(ptr->right);
}
q.pop();
}
}