|
| 1 | +package com.interview.tree; |
| 2 | + |
| 3 | +/** |
| 4 | + * Date 11/07/2015 |
| 5 | + * @author Tushar Roy |
| 6 | + * |
| 7 | + * Write class for interval tree |
| 8 | + * Keep a max at every node which is max of that subtree. |
| 9 | + * This max is used to decide which direction to move when checking |
| 10 | + * for overlap. When an interval's high is less than max of left side go |
| 11 | + * in that direciton otherwise go in other direction. |
| 12 | + */ |
| 13 | +class InternalNode { |
| 14 | + int low; |
| 15 | + int high; |
| 16 | + int max; |
| 17 | + InternalNode left; |
| 18 | + InternalNode right; |
| 19 | + |
| 20 | + @Override |
| 21 | + public String toString() { |
| 22 | + return "InternalNode{" + |
| 23 | + "max=" + max + |
| 24 | + ", low=" + low + |
| 25 | + ", high=" + high + |
| 26 | + '}'; |
| 27 | + } |
| 28 | +} |
| 29 | + |
| 30 | +public class IntervalTree { |
| 31 | + |
| 32 | + public InternalNode insert(InternalNode root, int low, int high) { |
| 33 | + if(root == null) { |
| 34 | + InternalNode node = new InternalNode(); |
| 35 | + node.low = low; |
| 36 | + node.high = high; |
| 37 | + node.max = high; |
| 38 | + return node; |
| 39 | + } |
| 40 | + |
| 41 | + if(low < root.low) { |
| 42 | + root.left = insert(root.left, low, high); |
| 43 | + } else { |
| 44 | + root.right = insert(root.right, low, high); |
| 45 | + } |
| 46 | + |
| 47 | + root.max = Math.max(root.high, high); |
| 48 | + return root; |
| 49 | + } |
| 50 | + |
| 51 | + public InternalNode isOverlap(InternalNode root, int low, int high) { |
| 52 | + if(root == null) { |
| 53 | + return null; |
| 54 | + } |
| 55 | + |
| 56 | + if(root.high >= low && root.low <= high) { |
| 57 | + return root; |
| 58 | + } |
| 59 | + |
| 60 | + if(root.left != null && root.left.max > low) { |
| 61 | + return isOverlap(root.left, low, high); |
| 62 | + } else { |
| 63 | + return isOverlap(root.right, low, high); |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + public static void main(String args[]) { |
| 68 | + IntervalTree it = new IntervalTree(); |
| 69 | + InternalNode root = null; |
| 70 | + root = it.insert(root, 10, 15); |
| 71 | + root = it.insert(root, 11, 13); |
| 72 | + root = it.insert(root, 18, 21); |
| 73 | + root = it.insert(root, 20, 25); |
| 74 | + root = it.insert(root, 0, 7); |
| 75 | + |
| 76 | + System.out.println(it.isOverlap(root, 8, 9)); |
| 77 | + System.out.println(it.isOverlap(root, 17, 17)); |
| 78 | + System.out.println(it.isOverlap(root, 21, 22)); |
| 79 | + System.out.println(it.isOverlap(root, 21, 22)); |
| 80 | + System.out.println(it.isOverlap(root, 12, 18)); |
| 81 | + System.out.println(it.isOverlap(root, 24, 26)); |
| 82 | + } |
| 83 | + |
| 84 | +} |
0 commit comments