Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I'm not sure with what you are trying to populate the Red Black Tree. But if you are using array or stream of data (whose number of elements will not change) then you may go this by using <a href="http://en.wikipedia.org/wiki/Segment_tree" rel="nofollow">Segment Tree</a> </p> <pre><code>class SegmentTree { class Node { int max, min, s, e; Node left, right; @Override public String toString() { String str = "Min: "+this.min+" Max: "+this.max+" "+this.s+"-"+this.e; return str; } } private Node root; public SegmentTree() {} public SegmentTree(int[] array) { add(array); } public void add(int[] array) { root = add(0, array.length-1, array); } private Node add(int s, int e, int[] array) { Node n = new Node(); n.s = s; n.e = e; if(n.s==n.e) { n.min = n.max = array[n.s]; return n; } int mid = s+(e-s)/2; n.left = add(s, mid, array); n.right = add(mid+1, e, array); n.max = Math.max(n.left.max, n.right.max); n.min = Math.min(n.left.min, n.right.min); return n; } // Get the max value between the limits l and r (both inclusive) public int getMax(int l, int r) { return getMax(root, l, r); } private int getMax(Node n, int l, int r) { if(l&lt;=n.s &amp;&amp; r&gt;=n.e) return n.max; if(l&gt;n.e || r&lt;n.s) return Integer.MIN_VALUE; return Math.max(getMax(n.left, l, r), getMax(n.right, l, r)); } public int getMin(int l, int r) { return getMin(root, l, r); } private int getMin(Node n, int l, int r) { if(l&lt;=n.s &amp;&amp; r&gt;=n.e) return n.min; if(l&gt;n.e || r&lt;n.s) return Integer.MAX_VALUE; return Math.min(getMin(n.left, l, r), getMin(n.right, l, r)); } } </code></pre> <p><strong>NOTE</strong> </p> <p>If there is increase or decrease in the data then you have to reconstruct the tree. If there is frequent insertion/ deletion/ updation then this is not at all a good choice.<br> This is very useful when you have set of data and on which you need to frequently check the values for the particular range.<br> I have given the example of storing both minimum and maximum value. You may store sum of values or any thing else in your <code>Node</code><br> Apologize for writing code in JAVA :)</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload