Question

In: Computer Science

I have code for an AVL tree. I Have have a node class and tree class....

I have code for an AVL tree. I Have have a node class and tree class. I need a  node object that refrences the root(top) of the tree. my current code throws NullPointerException when I try to access the root properties. here is the important snippets of my code, it is in java.

public class Node {
    private Node left=null,right=null;
    public int height=1;
    private String Item;
    private int balance=0; 
    Node(String item) { 
    this.Item=item; }
}
--------------------------------------------------
public class AVLTree {
    public Node root;
    public AVLTree(){
     root=null;
 }
public void insert(String str){
    AVLTree t = new AVLTree();
    root.setItem(str);
    root=t.insert(root,str);
}
public void delete(String str){
    AVLTree t = new AVLTree();
    root.setItem(str);
    t.deleteNode(root,str);
}
private Node insert(Node node, String str) {
    deleteNode(node, str);   
    if (node == null) {
        return(new Node(str));
    }
    if (str.compareTo(node.getItem()) <1)
        node.setLeft(insert(node.getLeft(),str));
    else
        node.setRight(insert(node.getRight(),str));
    node.height = Math.max(height(node.getLeft()), height(node.getRight())) + 1;
    int balance = getBalanceNode(node);
    if (balance > 1 && str.compareTo(node.getLeft().getItem())<1)
        return rightRotate(node);
    if (balance < -1 && str.compareTo(node.getRight().getItem())>1)
        return leftRotate(node);
    if (balance > 1 && str.compareTo(node.getLeft().getItem())>1)
    {
        node.setLeft(leftRotate(node.getLeft()));
        return rightRotate(node);
    }
    if (balance < -1 &&str.compareTo(node.getRight().getItem())<1)
    {
        node.setRight(rightRotate(node.getRight()));
        return leftRotate(node);
    }
    return node;
}
private Node deleteNode(Node node, String str) {
    if (node == null)
        return node;
    if (str.compareTo(node.getItem())<1)
        node.setLeft(deleteNode(node.getLeft(),str));
    else if( str.compareTo(node.getItem())>1)
        node.setRight(deleteNode(node.getRight(),str));
    else {
        if( (node.getLeft() == null) || (node.getRight() == null) ) {
            Node temp;
            if (node.getLeft() != null)
                temp = node.getLeft();
            else
                temp = node.getRight();
            if(temp == null) {
                temp = node;
                node = null;
            }
            else
                node = temp;
            temp = null;
        }
        else {
            Node temp = minValueNode(node.getRight());
            node.setItem(temp.getItem());
            node.setRight(deleteNode(node.getRight(),temp.getItem()));
        }
    }
    if (node == null)
        return node;
    node.height = Math.max(height(node.getLeft()), height(node.getRight())) + 1;
    int balance = getBalanceNode(node);
    if (balance > 1 && getBalanceNode(node.getLeft()) >= 0)
        return rightRotate(node);
    if (balance > 1 && getBalanceNode(node.getLeft()) < 0) {
        node.setLeft(leftRotate(node.getLeft()));
        return rightRotate(node);
    }
    // Right Right Case
    if (balance < -1 && getBalanceNode(node.getRight()) <= 0)
        return leftRotate(node);
    // Right Left Case
    if (balance < -1 && getBalanceNode(node.getRight()) > 0) {
        node.setRight(rightRotate(node.getRight()));
        return leftRotate(node);
    }
    return node;
}}

Solutions

Expert Solution

There are 3 points in your code which i think would result in the problem:-

1.) The following code:-

        Node(String item) { 
        this.Item=item; }

Could also lead to NullPointerException as

In your case, you are not creating the object item, but rather assuming that it was created before the Node() method was called.

Alternatively, there may be cases where the purpose of the method is not solely to operate on the passed in object, and therefore a null parameter may be acceptable. In this case, you would need to check for a null parameter and behave differently. For example, Node() could be written as:

        Node(String item) { 
          If(item!=null)
          {
            this.Item=item;
          }
          else{
            return item;
          } 
        }

NullPointerExceptions are exceptions that occur when you try to use a reference that points to no location in memory (null) as though it were referencing an object. Calling a method on a null reference or trying to access a field of a null reference will trigger a NullPointerException.

2.) Your code throws NullPointerException when you try to access root as there is no null check for root in your code. It should be:-

        if (root == null)
        return root;

As it is possible that root can be null. And than you are trying to access root properties of an object with reference to null which results in NullPointerExceptions.

3.) Same is with your left and right in Node class. Here you are declaring them to null and then you are trying to access their properties as:-

        node.getLeft()

This would result in NullPointerException as they are set to null and then you are trying to access their properties.


Related Solutions

1. Modify a binary search tree implementation code (that AVL tree code depends on) to print...
1. Modify a binary search tree implementation code (that AVL tree code depends on) to print out the data value for each node it encounters in the insert operation. Remember that the module AVL tree code gets part of its functionality from the BST type, since an AVL tree is a binary search tree, but adds some additional functionality. 2. Add code to the main method to meet the following requirements: (a) Create an AVL tree to hold names stored...
AVL tree; Insert and Range Minimum operation in Java code.
AVL tree; Insert and Range Minimum operation in Java code.
(IN C) Write the code to manage a Binary Tree. Each node in the binary tree...
(IN C) Write the code to manage a Binary Tree. Each node in the binary tree includes an integer value and string. The binary tree is sorted by the integer value. The functions include: • Insert into the binary tree. This function will take in as parameters: the root of the tree, the integer value, and the string. Note that this function requires you to create the node. • Find a node by integer value: This function takes in two...
Write code for O(n) worst-case algorithm that verifies that a tree is actually an AVL tree by detecting imbalance.
Write code for O(n) worst-case algorithm that verifies that a tree is actually an AVL tree by detecting imbalance. If imbalance is true, then call the proper rotation function provided in the lecture slides to fix the imbalance condition.1. Must read AVLNode data from a text file2. Create a Book Object; and an AVL node object to be inserted into the AVL tree3. At each insert, detect imbalance and fix the AVL tree4. Report each imbalance detection and the node...
C++ AVL tree My AVL tree function void inorder(AVLNode* t) { if (t == NULL) return;...
C++ AVL tree My AVL tree function void inorder(AVLNode* t) { if (t == NULL) return; inorder(t->left); cout << t->data.cancer_rate << " "; inorder(t->right); } void inorder() { inorder(root); } Will Print my cancer city rate Inorder example) 3.1 5.8 19.8 My question is how can I add a decreasing index to this function example) 3) 3.1 2)5.8 1)19.8
Create a (partial) BST class and a driver program to test it. The tree node will...
Create a (partial) BST class and a driver program to test it. The tree node will store integers as the data/key field (single field). Note that you will need to guarantee there are no duplicates in your insert function (the tree should refuse to insert a duplicate key). Call your files “tree.h”, “tree.cpp” and “main.cpp”. In addition, draw a picture of your tree (see note about random values below) Public methods to include: Constructor Copy Constructor Overloaded Assignment Operator Destructor...
Write the code to manage a Binary Tree. Each node in the binary tree includes an integer value and string.
Programming CWrite the code to manage a Binary Tree. Each node in the binary tree includes an integer value and string. The binary tree is sorted by the integer value. The functions include:• Insert into the binary tree. This function will take in as parameters: the root of the tree, the integer value, and the string. Note that this function requires you to create the node.• Find a node by integer value: This function takes in two parameters: the root...
1. Starting with an empty tree, show each step in the construction of an AVL tree...
1. Starting with an empty tree, show each step in the construction of an AVL tree using the following input in the order given. For full credit, you must show the tree after each new input is added. 16, 7, 14, 18, 6, 17, 2, 5, 13, 22, 4 (6 pts.) 2. Show how the AVL tree in previous changes with the following operations. For full credit, you must show the tree after each iteration. Remove: 17 Remove: 18 Remove:...
Implement a function to find a node in a binary search tree. Using the following class...
Implement a function to find a node in a binary search tree. Using the following class and function definition. If a node with a matching value is found, return a pointer to it. If no match is found, return nullptr. #include <iostream> class BTNode { public: int item; BTNode *left; BTNode *right; BTNode(int i, BTNode *l=nullptr, BTNode *r=nullptr):item(i),left(l),right(r){} }; BTNode *root = nullptr; BTNode *find(int item) { //implement code here return nullptr; } int main() {    root = new...
C++ finish the AVL Tree code: #include "AVLNode.h" #include "AVLTree.h" #include <iostream> #include <string> using namespace...
C++ finish the AVL Tree code: #include "AVLNode.h" #include "AVLTree.h" #include <iostream> #include <string> using namespace std; AVLTree::AVLTree() { root = NULL; } AVLTree::~AVLTree() { delete root; root = NULL; } // insert finds a position for x in the tree and places it there, rebalancing // as necessary. void AVLTree::insert(const string& x) { // YOUR IMPLEMENTATION GOES HERE } // remove finds x's position in the tree and removes it, rebalancing as // necessary. void AVLTree::remove(const string& x) {...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT