BinaryTreeNode

Hello,
I'm learning about binary trees and would like to create my own class implementing binary nodes.
I'm getting the following error:
"Illegal modifier for the class BinaryTreeNode; only public, abstract, & final are permitted"
Any ideas?
All I did was create a new class called BinaryTreeNode and started writing the code as follows:
protected class BinaryTreeNode<T>{

class cannot be made protected.
chnage the signature to
public class BinaryTreeNode<T>{
or just
class BinaryTreeNode<T>{                                                                                                                                                                                                                                                                               

Similar Messages

  • I need help with my remove method on a BST!

    Guys I need some help here, I have to create a remove method for a BST and below is my code:
    public boolean remove(OrderedMap map, K keyOfelementToRemove) {
              boolean result = false;
              if (root == null)
                   result = false;
              else {
                   MapNode curr = root;
                   MapNode prev = root;
                   while (curr.key.equals(keyOfelementToRemove) == false) {
                        prev = curr;
                        if (keyOfelementToRemove.compareTo(curr.key) < 0)
                             curr = curr.left;
                        else if (keyOfelementToRemove.compareTo(curr.key) > 0)
                             curr = curr.right;
                        if (curr == null)
                             break;
                   if (curr == null)
                        return result;
                   else if (curr == root && curr.left == null)
                        root = root.right;
                   else if (curr.left == null) {
                        if (curr.right == null)
                             curr = null;
                        else if (curr == prev.left)
                             prev = curr.right;
                        else if (curr == prev.right){
                             prev = curr.right;
                   else if (curr.left != null) {
                        MapNode temp = curr.left;
                        while (temp.right != null)
                             temp = temp.right;
                        K change = temp.key;
                        temp = null;
                        curr.key = change;
              size--;
              return result;
         }the algorithm that my instructor provides is:
    private boolean remove( BinaryTreeNode t, Comparable elementToRemove )
    Set result to false
    Traverse the tree t until elementToRemove is found. Use curr and prev to find the element
    leaving curr referring the node you want to remove. It may be the case that curr is null indicating
    that elementToRemove was not found. Now there are four cases to consider :
    Case 1: Not found
    return result (false)
    Case 2: The root is to be removed, but it has no left child.
    root = root's right subtree (assuming root refers the the root node in your BST)
    Case 3: The node is further down tree with no left child. Now must adjust one of the parent's links
    if curr is on the left side of prev,
    move parent's left link down to down to curr's right child
    else
    curr is on the right side of prev, so move parent's right down to down to curr's right child
    Case 4: curr has a left child.
    We can no longer ignore the left subtree. So find the maximum in the left subtree and
    move that object to the node referenced by curr . Then eliminate the maximum in the
    left subtree, which is now being reference from the original node to remove.
    however for case 3 and 4 it doesn't work, can someone please tell me why? I don't know where I made a mistake and I tried finding it but I still dont know

    I am sorry about the double post. I'll try not to do this again. My problem here seems to be that prev and curr aren't updating the BST outside this method, which means that it only changes locally but not permanently. I will post the code of the other headings:
    public class OrderedMap<K extends Comparable<K>, V> {
         private class MapNode {
              // Links to other BSTs
              private MapNode left;
              private MapNode right;
              ArrayList<V> temp1 = new ArrayList<V>();
              // The references to the key/value pair of the mapping
              private K key;
              @SuppressWarnings("unused")
              private V value;
              public MapNode(K theKey, V theValue) {
                   key = theKey;
                   value = theValue;
                   left = null;
                   right = null;
         } // end class MapNode
         private MapNode root;
         private int size;
         public OrderedMap() { // Create an empty tree
              root = null;
              size = 0;
         public int size() {
              return size;
         }

  • A question on a build method in a Binary Tree Program

    So I'm working on making 20 Questions in java and I'm supposed to make a construct that calls a build method.
    I'll post my code as I have it so far.
    The game is supposed to work so that there's an original question and then if the user selects yes, then the answer goes to the left link. The no answer goes to the right link and then it keeps going yes for the left, no for the right.
    How do I call the build method recursively to do that?
    public class GameTree {
    * BinaryTreeNode inner class used to create new nodes in the GameTree.
    private class BinaryTreeNode {
    private String data;
    private BinaryTreeNode left;
    private BinaryTreeNode right;
    BinaryTreeNode(String theData) {
    data = theData;
    left = null;
    right = null;
    BinaryTreeNode(String theData, BinaryTreeNode leftLink, BinaryTreeNode rightLink) {
    data = theData;
    left = leftLink;
    right = rightLink;
    * instance variables.
    private BinaryTreeNode root;
    private Scanner my_inputFile;
    private String currentFileName;
    private BinaryTreeNode currentNodeReferenceInTree;
    * Constructor needed to create the game.
    * @param name
    * this is the name of the file we need to import the game questions
    * and answers from.
    public GameTree(String name) {
    // TODO: Complete this method
         currentFileName = name;
         try {
              my_inputFile = new Scanner(new File(currentFileName));
         catch (FileNotFoundException e) {
         root = build();
         my_inputFile.close();
    public BinaryTreeNode build() {
         String token2 = my_inputFile.nextLine();
         if(!isQuestion(token2))
              return new BinaryTreeNode(token2);
         else{
              BinaryTreeNode rightTreeSide = build();
              BinaryTreeNode leftTreeSide = build();
              return new BinaryTreeNode(token2,leftTreeSide, rightTreeSide);
    * Ask the game to update the current node by going left for Choice.yes or
    * right for Choice.no Example code: theGame.playerSelected(Choice.Yes);
    * @param yesOrNo
    public void playerSelected(Choice yesOrNo) {
         if(userSelection == Choice.No)
              currentNodeReferenceInTree = currentNodeReferenceInTree.right;
         if(userSelection == Choice.Yes)
              currentNodeReferenceInTree = currentNodeReferenceInTree.left;
    I have a separate .java that already says
    public enum Choice {
    Yes, No
    };

    When you post code, wrap it in code tags so it's legible. When you're inputting the text, highlight it, and then click the "CODE" button above the text input box. It can be almost impossible to read code that's not formatted like that.
    You ask "How do I call the build method recursively to do that?" You don't call recursive methods any differently than you call any other kind of method. Can you clarify what difficulty you're having?

  • Emptying a Binary Tree

    Hello,
    The problem I'm having is how to empty a binary tree. Here is my code for MyBinaryTree:
    public class MyBinaryTree implements BinaryTree {
       private BinaryTreeNode root;
       protected static int numNodes;
       private static String tree = "";
        * Constructor that creates a binary tree with a root.
        * @param r The root node
        * @param num The number of nodes
       public MyBinaryTree(BinaryTreeNode r, int num) {
          root = r;
          numNodes = num;
        * Method to make the binary tree empty.
       public void makeEmpty() {
          root.left = null;
          root.right = null;
          root = new BinaryTreeNode(null,null,null,null,null);
          numNodes = 0;
        * Method to make a root with key k and element el.
        * @param k The key of the root
        * @param el The element in the root
       public void makeRoot(Comparable k, Object el) {
          root = new BinaryTreeNode(k,el);
          numNodes++;
        * Method to return the root of the binary tree.
        * @return The root of the tree
       public BinaryTreeNode root() {
          return root;
        * Method to return the left child of a node.
        * @param node The node whose left child is wanted.
        * @return The left child of the node
        * @see NoNodeException
       public BinaryTreeNode leftChild(BinaryTreeNode node) throws NoNodeException {
          if (node.left == null) throw new NoNodeException("No left child!");
          else return node.leftChild();
        * Method to set the left child of node "node".
        * @param node The node to be given a left child
        * @param child The node to be set as left child
       public void setLeftChild(BinaryTreeNode node, BinaryTreeNode child) {
          node.setLeftChild(child);
          numNodes++;
        * Method to return the right child of a node.
        * @param node The node whose right child is wanted.
        * @return The right child of the node
        * @see NoNodeException
       public BinaryTreeNode rightChild(BinaryTreeNode node) throws NoNodeException{
          if (node.right == null) throw new NoNodeException("No right child!");
          else return node.rightChild();
        * Method to set the right child of node "node".
        * @param node The node to be given a right child
        * @param child The node to be set as right child
       public void setRightChild(BinaryTreeNode node, BinaryTreeNode child) {
          node.setRightChild(child);
          numNodes++;
        * Method to return the parent of a node.
        * @param node The node whose parent is wanted.
        * @return The parent of the node
        * @see NoNodeException
       public BinaryTreeNode parent(BinaryTreeNode node) throws NoNodeException {
          if (node.p == null) throw new NoNodeException("No parent!");
          else return node.parent();
        * Method to set the parent of node "node".
        * @param node The node to be given a parent
        * @param pt The node to be set as parent
       public void setparent(BinaryTreeNode node, BinaryTreeNode pt) {
          node.setParent(pt);
          numNodes++;
        * Method to return the key of the specified node.
        * @param node The node with the key to be returned
        * @return The key of the node
       public Comparable getKey(BinaryTreeNode node) {
          return node.getKey();
        * Method to set the key of the specified node.
        * @param node The node for which the key will be set.
        * @param k The key to be set.
       public void setKey(BinaryTreeNode node, Comparable k) {
          node.setKey(k);
        * Method to get the element in the specified node.
        * @param node The node with the element to be returned.
        * @return The element in the node.
       public Object getElement(BinaryTreeNode node) {
          return node.getElement();
        * Method to put an element into the specified node.
        * @param node The node that will have an element put in it.
        * @param o The element to be inserted.
       public void setElement(BinaryTreeNode node, Object o) {
          node.setElement(o);
        * Method to add a left child to the specified node.
        * @param theNode The node that the left child will be added to.
        * @param k The key associated with the left child.
        * @param el The element in the left child.
       public void addLeftChild (BinaryTreeNode theNode, Comparable k, Object el) {
          BinaryTreeNode temp = new BinaryTreeNode(k,el);
          temp.setParent(theNode);
          theNode.setLeftChild(temp);
          numNodes++;
        * Method to add a right child to the specified node.
        * @param theNode The node that the right child will be added to.
        * @param k The key associated with the right child.
        * @param el The element in the right child.
       public void addRightChild (BinaryTreeNode theNode, Comparable k, Object el) {
          BinaryTreeNode temp = new BinaryTreeNode(k,el);
          temp.setParent(theNode);
          theNode.setRightChild(temp);
          numNodes++;
        * Method to remove the left child of the specified node.
        * @param theNode The node which the left child will be removed.
       public void removeLeftChild(BinaryTreeNode theNode) {
          ((BinaryTreeNode)(theNode.left)).p = null;
          theNode.left = null;
          numNodes--;
        * Method to remove the right child of the specified node.
        * @param theNode The node which the right child will be removed.
       public void removeRightChild(BinaryTreeNode theNode) {
          ((BinaryTreeNode)(theNode.right)).p = null;
          theNode.right = null;
          numNodes--;
        * Private method to perform an inorder traversal on the tree.
        * @param t A MyBinaryTree object
        * @param n The starting node.
       private static String inorderPrint(MyBinaryTree t, BinaryTreeNode n) {
          String spaces = "";
          for (int i = 0; i < (numNodes - 1)/2; i++) spaces += " ";
          if (n.left != null || n.right != null) inorderPrint(t,t.leftChild(n));
          tree += spaces + n.getElement();
          if (n.left != null || n.right != null) inorderPrint(t,t.rightChild(n));
          return tree;
        * Private method to perform an inorder traversal on the tree.
        * @param t A MyBinaryTree object
        * @param n The starting node.
        * @param pos The current position in the tree.
        * @return A tree with an asterix beside the current position
       private static String inorderPrint2(MyBinaryTree t, BinaryTreeNode n,
                                           BinaryTreeNode pos) {
          String spaces = "";
          for (int i = 0; i < (numNodes - 1)/2; i++) spaces += " ";
          if (n.left != null || n.right != null) inorderPrint2(t,t.leftChild(n),pos);
          if (n.getElement() == pos.getElement()) tree += spaces + n.getElement() + "*";
          else tree += spaces + n.getElement();
          if (n.left != null || n.right != null) inorderPrint2(t,t.rightChild(n),pos);
          return tree;
        * Method to return a String representation of the binary tree.
        * @return String representation of the binary tree
       public String toString() {
          if (root.getElement() == null) return "*** Tree is empty ***";
          else {
             MyBinaryTree temp = new MyBinaryTree(root,numNodes);
             return inorderPrint(temp,root);
        * Method to return a String of the binary tree with an asterix beside the
        * current position.
        * @param currentPosition The current position.
        * @return A String of the tree with an asterix by the current position
       public String toString(BinaryTreeNode currentPosition) {
          if (root.getElement() == null) return "*** Tree is empty ***";
          else {
             MyBinaryTree temp = new MyBinaryTree(root,numNodes);
             return inorderPrint2(temp,root,currentPosition);
    }Those are all the methods I'm allowed to have. When I run makeEmpty, it seems to work, but then if I do makeRoot, the old tree prints again. It's quite bizarre. Any tips on how to empty the tree correctly?

    Here is the BinaryTreeNode code.
    public class BinaryTreeNode {
        // Instance variables (Note: they are all "private")
        protected Comparable key;           // The key at this node
        protected Object element;          // The data at this node
        protected BinaryTreeNode left;     // Left child
        protected BinaryTreeNode right;    // Right child
        protected BinaryTreeNode p;        // The Parent
        // Constructors
        BinaryTreeNode( Comparable theKey, Object theElement, BinaryTreeNode lt,
                        BinaryTreeNode rt, BinaryTreeNode pt  ) {
            key      = theKey;
            element  = theElement;
            left     = lt;
            right    = rt;
            p        = pt;
        BinaryTreeNode( Comparable theKey, Object theElement) {
            key      = theKey;
            element  = theElement;
            left     = null;
            right    = null;
            p        = null;
        // return the key attached to this node
        public Comparable getKey() {
            return key;
        // set the key attached to this node to be Comparable k
        public void setKey(Comparable k) {
            key = k;
        // return the element attached to this node
        public Object getElement() {
            return element;
        // set the element attached to this node to be Object o
        public void setElement(Object o) {
            element = o;
        // return left child
        public BinaryTreeNode leftChild() {
            return left;
        // set left child to be node n
        public void setLeftChild(BinaryTreeNode n) {
            left = n;
        // return right child
        public BinaryTreeNode rightChild() {
            return right;
        // set right child to be node n
        public void setRightChild(BinaryTreeNode n) {
            right = n;
        // return parent
        public BinaryTreeNode parent() {
            return p;
        // set parent to be node n
        public void setParent(BinaryTreeNode n) {
            p = n;
    }

  • Unchecked or unsafe  error

    code]     private static void constructCodeTable(BinaryTreeNode btn,Stack st,Hashtable codeTable)
              if(btn!=null)
                   if(btn instanceof LeafNode)
                        codeTable.put(((InternalNode)btn).getKey(),st);
                   else
                        st.push(new Integer(0));
                        constructCodeTable(((InternalNode)btn).getLeftChild(),st,codeTable);
                        st.pop();
                        st.push(new Integer(1));
                        constructCodeTable(((InternalNode)btn).getRightChild(),st,codeTable);
                        st.pop();
    InternalNode.java and LeafNode.java extends BInaryNode.java
    InternalNode has function getLeftChild() and getRightChild()
    LeafNode.java has function getKey();
    when compiled , getting error:
    Note: uses unchecked or unsafe operations.
    Note: Recompile with -Xlint:unchecked for details..
    can anyone tell why?

    RTFM, look through older posts, and think for yourself.
    This has been asked (and answered) a thousand times before.
    P.S. it's not an error, it's a warning.

  • Binary tree find 2nd smallest

    Hi,
    What's a good approach to find the second smallest element in a tree given its root? find2ndSmallest(BinaryTreeNode root). root.left, root.right, root.element thanks!

    What?

  • Urgency help needed.

    I am a beginner of Java. Now I was trapped in a problem of making methods of contains and insert in BinaryTreeSearch problem.
    insert:Inserts a new node to the tree. The data of the new node is given as the parameter. The place for the addition is found in the same way as for contains, but this is even easier as we dont have to separately check when the node data is equal -> one comparison per node. Just search until we find a missing child and put the new node there. This method will also return the new root node for the subtree it was called upon.
    contains:Searches for the given data from this node and the subtrees of this node. If the data was found the method returns true, otherwise false.
    The code include three class as below:
    import java.util.*;
    public class BinaryTreeNode {
         private BinaryTreeNode left;
         private BinaryTreeNode right;
         private Object data;
         public final BinaryTreeNode getRight() {
              return right;
         public final void setRight(BinaryTreeNode tree) {
              right = tree;
         public final BinaryTreeNode getLeft() {
              return left;
         public final void setLeft(BinaryTreeNode tree) {
              left = tree;
         public final Object getData() {
              return data;
         public final void setData(Object data) {
              this.data = data;
    public class BinarySearchTree {
         private BSTNode root = null;
    public BSTNode getRoot(){
    return root;
         public void add(Comparable c) {
              if (root == null)
                   root = new BSTNode(c);
              else
                   root = root.insert(c);
         public void clear() {
              root = null;
         public boolean contains(Comparable c) {
              return (isEmpty()) ? false : root.contains(c);
         public boolean isEmpty() {
              return root == null;
    //public Iterator iterator() {
         //     return new InOrderIterator(root);
         public void remove(Comparable c) {
              if (root != null)
                   root = root.delete(c);
    import java.util.*;
    class BSTNode extends BinaryTreeNode {
         public BSTNode() {
    setData(null);
         public BSTNode(Comparable data) {
    setData(data);
    public BSTNode insert(Comparable data)
    if ( data.compareTo(this.getData())< 0)
    left = this.getLeft().insert(data);
    else if (data.compareTo(this.getData()) < 0)
    right =right.insert(data);
    else
    return this;
         public boolean contains(Comparable data)
              if (this == null)
              return false;
              if (data.compareTo(this.getData()) < 0)
    return (((BSTNode)this.getLeft()).contains(data));
              else if (data.compareTo(this.getData())> 0 )
    return (((BSTNode)this.getRight()).contains(data));
              else
                   return true;
    public BSTNode delete(Comparable data) {
              return null;      }
         public BSTNode intervalDelete(Comparable lowerLimit, Comparable upperLimit) {
         return null;     }
    public void printInorder(java.io.PrintStream pw){
         if(this.getLeft() != null)
              ((BSTNode)this.getLeft()).printInorder(pw);
         pw.println(this.getData());
         if(this.getRight() != null)
              ((BSTNode)this.getRight()).printInorder(pw);
    The contains and insert has some bug in executing, it can be return the right value as it should be.
    So any one could give me some suggestions. Thanks
    Gao
    [email protected]
    Message was edited by:
    Gorgen

    I am just new javaer, dont even know how to debug my
    program, when I make tester file, even more error
    comes out.A simple way to help you debug is to print out some information at critical parts of your program, like this:
    System.out.println("The value of someVariable is " + someVariable);This way you can tell if variables are holding the expected values, or if a particular code path is even executing at all.
    EDIT: Damn! Too slow again :(
    EDIT2: Wow, the auto-censor is really fu&#1089;ked-up in what it decides to censor.
    Message was edited by:
    Mr_Evil
    Message was edited by:
    Mr_Evil

  • Need help with BinaryTree

    hey guys,
    I'm working on an assignment that deals with binaryTree. I've few classes but in BinaryTreeNode class i've write few methods which will set a certain object/element to left and right node. Here's the code what i've so far and can someone help me to fill the empty method please, thanks in advance.
    public class BinaryTreeNode<T> {
        private T element;
        private BinaryTreeNode<T> left, right;
        //================================================================
        //  Creates a new tree node with the specified data.
        //================================================================
        BinaryTreeNode (T obj)  {
            element = obj;
            left = null;
            right = null;
        }  // constructor BinaryTreeNode
        //================================================================
        //  Returns the number of non-null children of this node.
        //  This method may be able to be written more efficiently.
        //================================================================
        public int numChildren() {
            int children = 0;
            if (left != null)
                children = 1 + left.numChildren();
            if (right != null)
                children = children + 1 + right.numChildren();
            return children;
        }  // method numChildren
         * i really don't know what to do here
       public void setLeft () {   }
       public void setRigh() { }
    }

    You don't know how to set an attribute?I know how to do that but what left and right will be equal too. They're set to null in the constructor, now i've to set a specific element to that left and right node.
    maybe something like this
    public void setLeft (BinaryTreeNode <T> node) { // i don't know what to do here } same goes for the othe rmethod

Maybe you are looking for