Search
 
SCRIPT & CODE EXAMPLE
 

CPP

Reverse Level Order Traversal cpp

/* 
	Reverse Level Order Traversal
*/
#include <bits/stdc++.h>
using namespace std;

/* A binary tree node has data,
pointer to left and right child */
class node
{
	public:
	int data;
	node* left;
	node* right;
};

/*Function prototypes*/
void printGivenLevel(node* root, int level);
int height(node* node);
node* newNode(int data);

/* Function to print REVERSE
level order traversal a tree*/
void reverseLevelOrder(node* root)
{
	int h = height(root);
	int i;
	for (i=h; i>=1; i--) //THE ONLY LINE DIFFERENT FROM NORMAL LEVEL ORDER
		printGivenLevel(root, i);
}

/* Print nodes at a given level */
void printGivenLevel(node* root, int level)
{
	if (root == NULL)
		return;
	if (level == 1)
		cout << root->data << " ";
	else if (level > 1)
	{
		printGivenLevel(root->left, level - 1);
		printGivenLevel(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 
";
	reverseLevelOrder(root);

	return 0;

}
Comment

PREVIOUS NEXT
Code Example
Cpp :: vector find 
Cpp :: comparator in sort c++ 
Cpp :: initialize dynamic array c++ to 0 
Cpp :: hello world in c/++ 
Cpp :: c++ ternary operator 
Cpp :: bubblesort c++ 
Cpp :: cin getline 
Cpp :: find kth max and min element in an array 
Cpp :: priority queue smallest first 
Cpp :: c++ filesystem read directory 
Cpp :: integer range in c++ 
Cpp :: stack overflow c++ 
Cpp :: c include 
Cpp :: doubly linked list in cpp 
Cpp :: c++ hello world linux 
Cpp :: sum of a matrix c++ 
Cpp :: c++ thread 
Cpp :: inserting element in vector in C++ 
Cpp :: cpp define 
Cpp :: vector iterating 
Cpp :: C++ :: 
Cpp :: how to write a template c++ 
Cpp :: string comparison c++ 
Cpp :: comparator priority queue c++ 
Cpp :: how to copy vector to another vector in c++ 
Cpp :: print Colored text in C++ 
Cpp :: why use python 
Cpp :: balanced parentheses 
Cpp :: call function from separate bash script 
Cpp :: move assignment operator c++ 
ADD CONTENT
Topic
Content
Source link
Name
8+4 =