Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.test.bst;
- /* this is the definition of the BST Node */
- class BSTNode{
- int key;
- BSTNode leftChild;
- BSTNode rightChild;
- public BSTNode(){}
- public BSTNode(int v){
- key = v;
- }
- }
- public class BST {
- /* returns the key of the current node */
- public int getkey(BSTNode n){
- return n.key;
- }
- /* returns the left child node or null if there isn't one */
- public BSTNode getLeftChild(BSTNode n){
- return n.leftChild;
- }
- /* returns the right child node or null if there isn't one */
- public BSTNode getRightChild(BSTNode n){
- return n.rightChild;
- }
- /* returns true if the Node is a leaf */
- public boolean isLeaf(BSTNode n) {
- return (n.leftChild==null)&&(n.rightChild==null);
- }
- /* To print the content of a BST in order, it
- * is sufficient an inorder visit
- */
- public static void printBST(BSTNode n, int deep){
- if(n.leftChild!=null)
- printBST(n.leftChild, deep+1);
- System.out.print("(" + n.key + ")");
- if(n.rightChild!=null)
- printBST(n.rightChild, deep+1);
- }
- public static void main(String[] args){
- /* Create a simple BST for testing purpose */
- BSTNode root = new BSTNode();
- root.key = 49;
- root.leftChild = new BSTNode(22);
- root.leftChild.leftChild = new BSTNode(17);
- root.leftChild.leftChild.rightChild = new BSTNode(20);
- root.rightChild = new BSTNode(82);
- root.rightChild.leftChild = new BSTNode(57);
- root.rightChild.rightChild = new BSTNode(88);
- root.rightChild.rightChild.rightChild = new BSTNode(94);
- root.rightChild.rightChild.rightChild.leftChild = new BSTNode(91);
- printBST(root,0);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement