From 371c065e1ba9172870fe3145591286dcc111f86b Mon Sep 17 00:00:00 2001 From: marizvi <202051121@iiitvadodara.ac.in> Date: Sun, 10 Oct 2021 22:54:17 +0530 Subject: [PATCH] reverse level order added --- binary_search_tree/revLevelOrder.java | 93 +++++++++++++++++++++++++++ 1 file changed, 93 insertions(+) create mode 100644 binary_search_tree/revLevelOrder.java diff --git a/binary_search_tree/revLevelOrder.java b/binary_search_tree/revLevelOrder.java new file mode 100644 index 00000000..3ee58ee1 --- /dev/null +++ b/binary_search_tree/revLevelOrder.java @@ -0,0 +1,93 @@ +package Binarytree; + +import java.util.*; + +class Nodes{ + int data; + Nodes left; + Nodes right; + Nodes(int element) + { + this.data = element; + this.left = this.right = null; + } +} + +class BST_REV{ + Nodes root; + BST_REV() + { + root = null; + } + void addNode(int element) + { + root = add(root,element); + } + Nodes add(Nodes node, int element) + { + if(node == null) + return new Nodes(element); + if(element<=node.data) + node.left = add(node.left,element); + else + if(element>node.data) + node.right = add(node.right,element); + + return node; + } + + ArrayList revLevelOrder() + { + return revLevelOrder(root); + } + ArrayList levelOrder() + { + return levelOrder(root); + } + ArrayList levelOrder(Nodes node) + { + ArrayList al = new ArrayList<>(); + Queue q = new LinkedList<>(); + q.add(node); + while(!q.isEmpty()) { + Nodes temp = q.remove(); + al.add(temp.data); + if(temp.left!=null) + q.add(temp.left); + if(temp.right!=null) + q.add(temp.right); + } + return al; + } + ArrayList revLevelOrder(Nodes node) + { + ArrayList al = new ArrayList<>(); + Queue q = new LinkedList<>(); + q.add(node); + while(!q.isEmpty()) { + Nodes temp = q.remove(); + al.add(temp.data); + if(temp.right!=null) + q.add(temp.right); + if(temp.left!=null) + q.add(temp.left); + } + Collections.reverse(al); + return al; + } + +} + +public class revLevelOrder { + public static void main(String[] args) { + BST_REV obj = new BST_REV(); + obj.addNode(9); + obj.addNode(6); + obj.addNode(13); + obj.addNode(5); + obj.addNode(7); + obj.addNode(11); + System.out.println("Level order Traversal of the entered tree is: "+obj.levelOrder()); + System.out.println("Reverse Level order of the tree is: "+obj.revLevelOrder()); + } +}