Site icon

Print binary tree in reverse order – level order traversal (BFS/ java/example)

Fig 1: Traverse binary tree

Brief algorithm: binary tree in reverse order (non recursive) in java

Fig 2: Stack View

Algorithm – binary in reverse order (breadth first search) using java

Fig 3: level order traversal of binary tree

Time complexity of algorithm is O(n).

Program – binary tree in reverse order (BFS) using java

1.) ReverseLevelOrder class: 

 package org.learn.Question;

import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;

import org.learn.PrepareTree.Node;

public class ReverseLevelOrder {

	public static void reverseLevelOrder(Node root) {
		if (root == null) {
			System.out.println("Tree is empty");
			return;
		}
		Queue<Node> queue = new LinkedList<Node>();
		queue.offer(root);
		Stack <Node> stack = new Stack<Node>();
		while (!queue.isEmpty()) {
			Node node = queue.poll();
			stack.push(node);
			if (node.left != null) {
				queue.offer(node.left);
			}
			if (node.right != null) {
				queue.offer(node.right);
			}
		}
		while(!stack.isEmpty()) {
			System.out.printf("%d ",stack.pop().data);
		}
	}
}

2.) Node Class: 

Node class representing the nodes of  a binary tree. Node class has following attributes

package org.learn.Question;

public class Node {
	public int data;
	public Node left;
	public Node right;

	public Node(int num) {
		this.data = num;
		this.left = null;
		this.right = null;
	}

	public Node() {
		this.left = null;
		this.right = null;
	}
	
	public static Node createNode(int number) {
		return new Node(number);
	}
}

3.) App Class: 

package org.learn.Client;

import org.learn.Question.Node;
import org.learn.Question.ReverseLevelOrder;

public class App {
	public static void main(String[] args) {
                // root level 0
		Node A = Node.createNode(60);
		// Level 1
		Node B = Node.createNode(50);
		Node C = Node.createNode(90);
		// Level 2
		Node D = Node.createNode(25);
		Node E = Node.createNode(80);
		Node F = Node.createNode(75);
		Node G = Node.createNode(45);

		// connect Level 0 and 1
		A.left = B;
		A.right = C;
		// connect level 1 and level 2
		B.left = D;
		B.right = E;
		C.left = F;
		C.right = G;
		System.out.println("Reverse Level Order Traversal:");
		ReverseLevelOrder.reverseLevelOrder(A);
	}
}

Output – reverse level order traversal of  binary tree using java

Reverse Level Order Traversal:
45 75 80 25 90 50 60

Code – binary tree in reverse order Level Order Traversal(BFS)

Exit mobile version