Advertisement
fbcyborg

BST Class

Oct 25th, 2012
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.60 KB | None | 0 0
  1. package com.test.bst;
  2.  
  3. /* this is the definition of the BST Node */
  4. class BSTNode{
  5.     int key;
  6.     BSTNode leftChild;
  7.     BSTNode rightChild;
  8.     public BSTNode(){}
  9.     public BSTNode(int v){
  10.         key = v;
  11.     }
  12. }
  13.  
  14. public class BST {
  15.    
  16.     /* returns the key of the current node */
  17.     public int getkey(BSTNode n){
  18.         return n.key;
  19.     }
  20.    
  21.     /* returns the left child node or null if there isn't one */
  22.     public BSTNode getLeftChild(BSTNode n){
  23.         return n.leftChild;
  24.     }
  25.    
  26.     /* returns the right child node or null if there isn't one */
  27.     public BSTNode getRightChild(BSTNode n){
  28.         return n.rightChild;
  29.     }
  30.    
  31.     /* returns true if the Node is a leaf */
  32.     public boolean isLeaf(BSTNode n) {
  33.         return (n.leftChild==null)&&(n.rightChild==null);
  34.     }
  35.    
  36.     /* To print the content of a BST in order, it
  37.      * is sufficient an inorder visit
  38.      */
  39.     public static void printBST(BSTNode n, int deep){
  40.         if(n.leftChild!=null)
  41.             printBST(n.leftChild, deep+1);
  42.        
  43.         System.out.print("(" + n.key + ")");
  44.        
  45.         if(n.rightChild!=null)
  46.             printBST(n.rightChild, deep+1);
  47.     }
  48.    
  49.     public static void main(String[] args){
  50.         /* Create a simple BST for testing purpose */
  51.         BSTNode root = new BSTNode();
  52.         root.key = 49;
  53.         root.leftChild = new BSTNode(22);
  54.         root.leftChild.leftChild = new BSTNode(17);
  55.         root.leftChild.leftChild.rightChild = new BSTNode(20);
  56.         root.rightChild = new BSTNode(82);
  57.         root.rightChild.leftChild = new BSTNode(57);
  58.         root.rightChild.rightChild = new BSTNode(88);
  59.         root.rightChild.rightChild.rightChild = new BSTNode(94);
  60.         root.rightChild.rightChild.rightChild.leftChild = new BSTNode(91);
  61.         printBST(root,0);
  62.     }
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement