Give an algorithm for printing the level order data in reverse order.

package in.blogspot.arunj2ee.ds.tree.binary.que;

import in.blogspot.arunj2ee.ds.tree.BinaryTreeNode;
import in.blogspot.arunj2ee.ds.tree.util.BTreePrinter;
import in.blogspot.arunj2ee.ds.tree.util.TreeUtil;

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

/**
 * Que: Give an algorithm for printing the level order data in reverse order.
 * Time Complexity:O(n), Space Complexity:O(n)
 * 48      
  / \  
 /   \
 35   85  
/ \ / \
60 78 52 19
               
Output: 19 52 78 60 85 35 48
 * @author Arun.Singh
 *
 */
public class Que9 {
public static void levelOrderTraversalInReverse(BinaryTreeNode root){
if(root == null)
return;
Stack<BinaryTreeNode> s = new Stack<BinaryTreeNode>();
Queue<BinaryTreeNode> q = new LinkedList<BinaryTreeNode>();
q.offer(root);

while(!q.isEmpty()){
BinaryTreeNode tmp = q.poll();
s.push(tmp);

if(tmp.getLeft() != null)
q.offer(tmp.getLeft());

if(tmp.getRight() != null)
q.offer(tmp.getRight());
}

while(!s.isEmpty()){
System.out.print(s.pop().getData() + " ");
}
}

public static void main(String []args){
BinaryTreeNode rootNode = TreeUtil.createRandomBinaryTree();
BTreePrinter.printBinaryTreeNode(rootNode);
levelOrderTraversalInReverse(rootNode);
}
}
========================================================================
Refer Core Classes: http://arunj2ee.blogspot.in/2017/05/tree-core-and-utility-classes.html
========================================================================
Share on Google Plus

About Admin

Arun is a JAVA/J2EE developer and passionate about coding and managing technical team.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment