Advertisement
Guest User

Untitled

a guest
Apr 23rd, 2014
39
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.06 KB | None | 0 0
  1. D D
  2. / /
  3. A S --> A S
  4. / /
  5. N N Z
  6. (size = 4) (size = 5)
  7.  
  8. public static class BSTNode
  9. {
  10. public BSTNode leftTree = null;
  11. public BSTNode rightTree = null;
  12. public int subtreeSize = 1;
  13. public int value;
  14.  
  15. public BSTNode(int valToAdd){
  16. value = valToAdd;
  17. }
  18. }
  19.  
  20. public static class BST
  21. {
  22. public BSTNode root;
  23.  
  24. //public void insert(int valToAdd)
  25. }
  26.  
  27. public void insert(int valToAdd)
  28. {
  29. if(root == null){
  30. root = new BSTNode(valToAdd);
  31. return;
  32. }
  33.  
  34. BSTNode parent = root;
  35. BSTNode current = root;
  36. while(current != null){
  37. parent = current;
  38. ++current.subtreeSize;
  39. if(valToAdd <= current.value){
  40. current = current.leftTree;
  41. }
  42. else{
  43. current = current.rightTree;
  44. }
  45. }
  46.  
  47. if(valToAdd <= parent.value){
  48. parent.leftTree = new BSTNode(valToAdd);
  49. }
  50. else{
  51. parent.rightTree = new BSTNode(valToAdd);
  52. }
  53. }
  54.  
  55. public static class BSTNode
  56. {
  57. public BSTNode leftTree = null;
  58. public BSTNode rightTree = null;
  59. public int height = 0;
  60. public int value;
  61.  
  62. public BSTNode(int valToAdd){
  63. value = valToAdd;
  64. }
  65. }
  66.  
  67. public void insert(int valToAdd)
  68. {
  69. if(root == null){
  70. root = new BSTNode(valToAdd);
  71. return;
  72. }
  73.  
  74. java.util.Stack<BSTNode> stack = new java.util.Stack<BSTNode>();
  75.  
  76. BSTNode parent = root;
  77. BSTNode current = root;
  78. while(current != null){
  79. parent = current;
  80. stack.push(current);
  81. if(valToAdd <= current.value){
  82. current = current.leftTree;
  83. }
  84. else{
  85. current = current.rightTree;
  86. }
  87. }
  88.  
  89. if(valToAdd <= parent.value){
  90. parent.leftTree = new BSTNode(valToAdd);
  91. }
  92. else{
  93. parent.rightTree = new BSTNode(valToAdd);
  94. }
  95.  
  96. int height = 1;
  97. while(!stack.isEmpty()){
  98. current = stack.pop();
  99. current.height = Math.max(height, current.height);
  100. ++height;
  101. }
  102. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement