Guest User

Untitled

a guest
Jul 21st, 2018
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.09 KB | None | 0 0
  1. class BTree {
  2. public class Node
  3. {
  4. int content;
  5. Node left, right;
  6.  
  7. Node(int content,
  8. Node left,
  9. Node right)
  10. {
  11. this.content = content;
  12. this.left = left;
  13. this.right = right;
  14. }
  15.  
  16. public String toString()
  17. {
  18. return ""+content;
  19. }
  20. }
  21.  
  22. Node root;
  23.  
  24. BTree() {
  25. this.root = null;
  26. }
  27.  
  28. BTree(int value) {
  29. this.root =
  30. new Node(value, null, null);
  31. }
  32.  
  33. void insertSorted(int value)
  34. {
  35. if (root == null)
  36. {
  37. root = new Node(value, null, null);
  38. }
  39. else
  40. {
  41. insertSorted(value, root);
  42. }
  43. }
  44.  
  45. void insertSorted(int value, Node e)
  46. {
  47. if (value < e.content)
  48. {
  49. if (e.left == null)
  50. {
  51. e.left = new Node(value, null, null);
  52. }
  53. else
  54. {
  55. insertSorted(value, e.left);
  56. }
  57. }
  58. else
  59. {
  60. if (e.right == null)
  61. {
  62. e.right = new Node(value, null, null);
  63. }
  64. else
  65. {
  66. insertSorted(value, e.right);
  67. }
  68. }
  69. }
  70.  
  71. void printInOrder()
  72. {
  73. System.out.print("In-Order: (");
  74. printInOrder(root);
  75. System.out.println(")");
  76. }
  77.  
  78. void printInOrder(Node e)
  79. {
  80. if (e != null)
  81. {
  82. printInOrder(e.left);
  83. System.out.print(e.content+" ");
  84. printInOrder(e.right);
  85. }
  86. }
  87.  
  88. List getNodeList()
  89. {
  90. List l = new List();
  91. getNodeList(l, root);
  92. return l;
  93. }
  94.  
  95. void getNodeList(List l, Node e)
  96. {
  97. if (e != null)
  98. {
  99. getNodeList(l, e.left);
  100. l.insertLast(e.content);
  101. getNodeList(l, e.right);
  102. }
  103. }
  104.  
  105.  
  106. public static void main(String[] args)
  107. {
  108. BTree tree = new BTree();
  109. tree.insertSorted(8);
  110. tree.insertSorted(3);
  111. tree.insertSorted(6);
  112. tree.insertSorted(2);
  113. tree.insertSorted(13);
  114. tree.insertSorted(-1);
  115. tree.insertSorted(5);
  116. tree.insertSorted(7);
  117. tree.insertSorted(4);
  118. tree.insertSorted(10);
  119.  
  120. tree.printInOrder();
  121.  
  122. List l = tree.getNodeList();
  123. l.print();
  124. }
  125. }
Add Comment
Please, Sign In to add comment