|
| 1 | +package section21_SegmentTrees; |
| 2 | + |
| 3 | +public class SegmentTree { |
| 4 | + |
| 5 | + private class Node { |
| 6 | + int data; |
| 7 | + int startInterval; |
| 8 | + int endInterval; |
| 9 | + Node left; |
| 10 | + Node right; |
| 11 | + } |
| 12 | + |
| 13 | + Node root; |
| 14 | + |
| 15 | + public SegmentTree(int[] arr) { |
| 16 | + this.root = constructTree(arr, 0, arr.length - 1); |
| 17 | + } |
| 18 | + |
| 19 | + private Node constructTree(int[] arr, int si, int ei) { |
| 20 | + if (si == ei) { |
| 21 | + Node baseResult = new Node(); // leaf Node |
| 22 | + baseResult.data = arr[si]; |
| 23 | + baseResult.startInterval = si; |
| 24 | + baseResult.endInterval = ei; |
| 25 | + |
| 26 | + return baseResult; |
| 27 | + } |
| 28 | + Node node = new Node(); |
| 29 | + node.startInterval = si; |
| 30 | + node.endInterval = ei; |
| 31 | + |
| 32 | + int mid = (si + ei) / 2; |
| 33 | + node.left = constructTree(arr, si, mid); |
| 34 | + node.right = constructTree(arr, mid + 1, ei); |
| 35 | + |
| 36 | + node.data = node.left.data + node.right.data; |
| 37 | + |
| 38 | + return node; |
| 39 | + } |
| 40 | + |
| 41 | + public void display() { |
| 42 | + this.display(this.root); |
| 43 | + } |
| 44 | + |
| 45 | + private void display(Node node) { |
| 46 | + if (node.left == null && node.right == null) { |
| 47 | + System.out.println("No left child => " + node.data + " <= No right child"); |
| 48 | + return; |
| 49 | + } |
| 50 | + String str = ""; |
| 51 | + if (node.left != null) { |
| 52 | + str += "[" + node.left.startInterval + "-" + node.left.endInterval + "] " + node.left.data + " => "; |
| 53 | + } else { |
| 54 | + str = str + "No left Child"; |
| 55 | + } |
| 56 | + str += " [" + node.startInterval + "-" + node.endInterval + "] " + node.data; |
| 57 | + |
| 58 | + if (node.right != null) { |
| 59 | + str += " <= [" + node.right.startInterval + "-" + node.right.endInterval + "] " + node.right.data; |
| 60 | + } else { |
| 61 | + str = str + " No right Child"; |
| 62 | + } |
| 63 | + System.out.println(str); |
| 64 | + |
| 65 | + display(node.left); |
| 66 | + display(node.right); |
| 67 | + } |
| 68 | +} |
0 commit comments