fork(5) download
  1. import java.util.*;
  2. import java.math.*;
  3. import java.io.*;
  4.  
  5. class Ideone {
  6. public static void main(String[] args){
  7. new Ideone().run();
  8. }
  9.  
  10. void run(){
  11. Obj root = new Obj(1);
  12. root = insertVal(root, 4);
  13. root = insertVal(root, 7);
  14. root = insertVal(root, 9);
  15. root = insertVal(root, 12);
  16. root = insertVal(root, 13);
  17. root = insertVal(root, 43);
  18. root = insertVal(root, 45);
  19. System.out.println(floor(root, 15));
  20. }
  21.  
  22. int floor(Obj root, int val){
  23. int ans = Integer.MIN_VALUE;
  24. boolean found = false;
  25. while(root != null){
  26. if(root.val==val){
  27. return val;
  28. }
  29. if(val < root.val){
  30. root = root.left;
  31. }else{
  32. found = true;
  33. ans = root.val;
  34. root = root.right;
  35. }
  36. }
  37. if(!found){
  38. throw new RuntimeException("There is no smaller value than " + val + " in the BST");
  39. }
  40. return ans;
  41. }
  42.  
  43. Obj insertVal(Obj root, int val){
  44. if(root==null){
  45. return new Obj(val);
  46. }
  47. if(val < root.val){
  48. root.left = insertVal(root.left, val);
  49. }else{
  50. root.right = insertVal(root.right, val);
  51. }
  52. return root;
  53. }
  54. }
  55. class Obj{
  56. int val;
  57. Obj right;
  58. Obj left;
  59.  
  60. public Obj(int val){
  61. this.val = val;
  62. right = left = null;
  63. }
  64.  
  65. public String toString(){
  66. return val + " ";
  67. }
  68. }
  69.  
Success #stdin #stdout 0.06s 380160KB
stdin
Standard input is empty
stdout
13