avl tree to store strings code example

Example: AVL TREE JAVA to store string

public AVLNode search(String key)
   {
      // Tree is empty
      if (root == null)
      {
            return null;
        }

      // Tree is not empty
      AVLNode p = root;
      try
      {while (true)
      {
            if(p == null && p.getData().equals(key))
            {
                break;
            }
            else if (key.compareTo(p.getData()) < 0)
            {
                p = p.getLeftChild();
            }
            else
            {
                p = p.getRightChild();
            }
      }
      }

      catch(NullPointerException e)
      {
          System.out.println(e);
      }
      return p;
   }

    // INSERT A NODE INTO AVL TRRE
    public void insert(String data) 
    {
        // Case: tree is empty  <------------------------------
        if (root == null)
        {
            root = new AVLNode(data);
            return;
        }

        // Case: tree is not empty
        AVLNode p = root;

        // move p down as far as we can
        while(true)
        {
            if (data.equals(p.getData()) && p.getLeftChild() != null)
            {
                p = p.getLeftChild();
            }

            else if(data.compareTo(p.getData()) < 0 && p.getLeftChild() != null)
            {
                p = p.getLeftChild();
            }
            else if (data.compareTo(p.getData()) > 0 && p.getRightChild() != null)
            {
                p = p.getRightChild();
            }
            else
            {
                break;
            }
        }

        // insert new node to the tree as a child of node p

        AVLNode newNode= new AVLNode(data);

        if(data.equals(p.getData()))
        {
            p.setLeftChild(newNode);
        }

        else if (data.compareTo(p.getData()) < 0)
        {
            p.setLeftChild(newNode);
        }
        else
        {
            p.setRightChild(newNode);
        }

        rebalanceInsertionPath(newNode);
    }

Tags:

Java Example