Created
April 3, 2016 05:58
-
-
Save deyindra/713ef7960ef5dd72f4bd7222ff7acf96 to your computer and use it in GitHub Desktop.
Floor and Ceil Value in BST
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class TreeNode<E> { | |
private E data; | |
private TreeNode<E> left; | |
private TreeNode<E> right; | |
public TreeNode(E data) { | |
this.data = data; | |
} | |
public TreeNode<E> addLeft(TreeNode<E> left){ | |
this.left = left; | |
return this; | |
} | |
public TreeNode<E> addRight(TreeNode<E> right){ | |
this.right = right; | |
return this; | |
} | |
public TreeNode<E> getLeft() { | |
return left; | |
} | |
public TreeNode<E> getRight() { | |
return right; | |
} | |
public E getData() { | |
return data; | |
} | |
@Override | |
public boolean equals(Object o) { | |
if (this == o) return true; | |
if (o == null || getClass() != o.getClass()) return false; | |
TreeNode<?> treeNode = (TreeNode<?>) o; | |
if (data != null ? !data.equals(treeNode.data) : treeNode.data != null) return false; | |
return true; | |
} | |
@Override | |
public int hashCode() { | |
return data != null ? data.hashCode() : 0; | |
} | |
@Override | |
public String toString() { | |
return data.toString(); | |
} | |
} | |
public static <E extends Comparable<E>> E ceil(TreeNode<E> node, E value){ | |
TreeNode<E> smaller = null; | |
while (node!=null){ | |
int cmp = value.compareTo(node.getData()); | |
if(cmp==0){ | |
return value; | |
}else if(cmp<0){ | |
smaller=node; | |
node=node.getLeft(); | |
}else{ | |
node=node.getRight(); | |
} | |
} | |
return smaller==null?null:smaller.getData(); | |
} | |
public static <E extends Comparable<E>> E floor(TreeNode<E> node, E value){ | |
TreeNode<E> larger = null; | |
while (node!=null){ | |
int cmp = value.compareTo(node.getData()); | |
if(cmp==0){ | |
return value; | |
}else if(cmp>0){ | |
larger=node; | |
node=node.getRight(); | |
}else{ | |
node=node.getLeft(); | |
} | |
} | |
return larger==null?null:larger.getData(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment