Guest User

Untitled

a guest
Jul 18th, 2018
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.94 KB | None | 0 0
  1. public class BST {
  2.     public BST(int i) // constructor: Root node added at the time of creation of
  3.     // the tree
  4.     {
  5.         rootNode = new BstNode(i);
  6.     }
  7.    
  8.     public void traverseAndPrint(BstNode currentNode) {
  9.         System.out.print("data = " + currentNode.intData);
  10.         // To aid in your understanding, you may want to just ignore this
  11.         // indented portion and just print the integer. In that case, change the
  12.         // line above to a println instead of a print.
  13.         if (currentNode.leftNode == null) {
  14.             System.out.print(" left = null");
  15.         } else {
  16.             System.out.print(" left = " + (currentNode.leftNode).intData);
  17.         }
  18.         if (currentNode.rightNode == null) {
  19.             System.out.print(" right = null");
  20.         } else {
  21.             System.out.print(" right = " + (currentNode.rightNode).intData);
  22.         }
  23.         System.out.println("");
  24.         if (currentNode.leftNode != null)
  25.             traverseAndPrint(currentNode.leftNode);
  26.         if (currentNode.rightNode != null)
  27.             traverseAndPrint(currentNode.rightNode);
  28.     }
  29.    
  30.     public void addNode(int i) {
  31.         BstNode currentNode = rootNode;
  32.         boolean finished = false;
  33.         do {
  34.             BstNode curLeftNode = currentNode.leftNode;
  35.             BstNode curRightNode = currentNode.rightNode;
  36.             int curIntData = currentNode.intData;
  37.             if (i > curIntData) // look down the right branch
  38.             {
  39.                 if (curRightNode == null) { // create a new node referenced with
  40.                     // currentNode.rightNode
  41.                     currentNode.rightNode = new BstNode(i);
  42.                     finished = true;
  43.                 } else // keep looking by assigning a new current node one level
  44.                 // down
  45.                 {
  46.                     currentNode = currentNode.rightNode;
  47.                 }
  48.             } else // look down the left branch
  49.             {
  50.                 if (curLeftNode == null) { // create a new node referenced with
  51.                     //  currentNode.leftNode
  52.                     currentNode.leftNode = new BstNode(i);
  53.                     finished = true;
  54.                 } else { // keep looking by assigning a new current node one
  55.                     currentNode = currentNode.leftNode;
  56.                 }
  57.             }
  58.         } while (!finished);
  59.     }
  60.  
  61.     BstNode rootNode;
  62.  
  63.    
  64. }
Add Comment
Please, Sign In to add comment