Showing posts with label PrintDataInReverseOrder. Show all posts
Showing posts with label PrintDataInReverseOrder. Show all posts

Sunday, 14 October 2018

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

For example, the output for the below tree should be: 4 5 6 7 2 3 1

public class PrintDataInReverseOrder {
    public static void main(String args[]) {
             Node rootNode = new Node("1");
             rootNode.left = new Node("2");
             rootNode.left.left = new Node("4");
             rootNode.left.right = new Node("5");
             rootNode.right = new Node("3");
             rootNode.right.right = new Node("7");
             rootNode.right.left = new Node("6");
           
             printInreverse(rootNode);
    }
   
    static void printInreverse(Node node) {
       
        Queue<Node> queue = new LinkedBlockingQueue<>();
        queue.add(node);
        Stack<String> stack = new Stack<>();
        while(!queue.isEmpty()) {
            Node node1 = queue.remove();
            stack.add(node1.value);
            if(null!=node1.right) {
                queue.add(node1.right);
            }
            if(null!=node1.left) {
                queue.add(node1.left);
            }
        }
       
        while(!stack.isEmpty()) {
            System.out.print(stack.pop());
        }
    }
}

class BinayTree{
    static class Node{
        String value;
        Node left;
        Node right;
       
        Node(String val){
            value = val;
            left = right = null;
        }
       
    }
   
}

output: 4567231

links for Data Structure

  1) 𝐁𝐞𝐜𝐨𝐦𝐞 𝐌𝐚𝐬𝐭𝐞𝐫 𝐢𝐧 𝐋𝐢𝐧𝐤𝐞𝐝 𝐋𝐢𝐬𝐭:  https://lnkd.in/gXQux4zj 2) 𝐀𝐥𝐥 𝐭𝐲𝐩𝐞𝐬 𝐨𝐟 𝐓𝐫𝐞𝐞 𝐓𝐫𝐚𝐯𝐞𝐫𝐬𝐚𝐥𝐬...