Guest User

Untitled

a guest
May 23rd, 2018
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.48 KB | None | 0 0
  1. import java.util.ArrayList;
  2.  
  3. public class BinarySearchTree {
  4. public static Node root;
  5.  
  6. public static ArrayList<Integer> arrayList;
  7.  
  8. public BinarySearchTree(){
  9. this.root = null;
  10. }
  11.  
  12. public void savePreOrder(Node root){
  13. if(root == null) return ;
  14.  
  15. arrayList.add(root.data);
  16.  
  17. savePreOrder(root.left);
  18. savePreOrder(root.right);
  19. }
  20.  
  21. public void insert(int number){
  22. Node newNode = new Node(number);
  23.  
  24. if(root == null){
  25. root = newNode;
  26. return ;
  27. }
  28.  
  29. Node current = root;
  30. Node parent = null;
  31.  
  32. while(true){
  33. parent = current;
  34. if(number < current.data){
  35. current = current.left;
  36. if(current == null){
  37. parent.left = newNode;
  38. return ;
  39. }
  40. } else {
  41. current = current.right;
  42. if(current == null){
  43. parent.right = newNode;
  44. return ;
  45. }
  46. }
  47. }
  48. }
  49.  
  50. public static void main(String[] args){
  51. BinarySearchTree bst = new BinarySearchTree();
  52. bst.insert(25);
  53. bst.insert(15);
  54. bst.insert(50);
  55. bst.insert(22);
  56. bst.insert(70);
  57. bst.insert(35);
  58. bst.insert(10);
  59. bst.savePreOrder(bst.root);
  60. for(int i = 0; i < arrayList.size(); i++) {
  61. System.out.println(arrayList.get(i));
  62. }
  63. }
  64. }
Add Comment
Please, Sign In to add comment