|
| 1 | +// Program to create a Binary Search Tree and implement level order traversal. |
| 2 | +// Author: Viveka Aggarwal |
| 3 | + |
| 4 | +import java.util.LinkedList; |
| 5 | +import java.util.Queue; |
| 6 | + |
| 7 | +public class treelevelorderprint { |
| 8 | + node root; |
| 9 | + class node { |
| 10 | + Integer value; |
| 11 | + node left; |
| 12 | + node right; |
| 13 | + |
| 14 | + node() { |
| 15 | + } |
| 16 | + |
| 17 | + node (Integer value) { |
| 18 | + this.value = value; |
| 19 | + } |
| 20 | + } |
| 21 | + |
| 22 | + public treelevelorderprint() { |
| 23 | + root = new node(); |
| 24 | + } |
| 25 | + |
| 26 | + public treelevelorderprint(Integer value) { |
| 27 | + root = new node(value); |
| 28 | + } |
| 29 | + |
| 30 | + public void addToTree(Integer value) { |
| 31 | + if (root.value == null) { |
| 32 | + root = new node(value); |
| 33 | + } else { |
| 34 | + addToTree(value, root); |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + public void addToTree(Integer value, node curr) { |
| 39 | + if (value <= curr.value) { |
| 40 | + if (curr.left == null) |
| 41 | + curr.left = new node(value); |
| 42 | + else |
| 43 | + addToTree(value, curr.left); |
| 44 | + } else { |
| 45 | + if (curr.right == null) |
| 46 | + curr.right = new node(value); |
| 47 | + else |
| 48 | + addToTree(value, curr.right); |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + public void levelOrder() { |
| 53 | + if (root == null || root.value == null) { |
| 54 | + System.out.println(); |
| 55 | + System.out.println("Empty tree!!!"); |
| 56 | + return; |
| 57 | + } |
| 58 | + |
| 59 | + Queue<node> q = new LinkedList<node>(); |
| 60 | + q.add(root); |
| 61 | + |
| 62 | + while(!q.isEmpty()) { |
| 63 | + node curr = q.poll(); |
| 64 | + System.out.print(curr.value + " "); |
| 65 | + |
| 66 | + if(curr.left != null) |
| 67 | + q.add(curr.left); |
| 68 | + |
| 69 | + if(curr.right != null) |
| 70 | + q.add(curr.right); |
| 71 | + } |
| 72 | + } |
| 73 | + |
| 74 | + public static void main(String[] args) { |
| 75 | + treelevelorderprint tree = new treelevelorderprint(); |
| 76 | + for (int i = 0; i <= 10; i++) { |
| 77 | + tree.addToTree(i); |
| 78 | + } |
| 79 | + tree.addToTree(5); |
| 80 | + tree.levelOrder(); |
| 81 | + } |
| 82 | +} |
0 commit comments