Ошибка StackOverFlow при попытке удалить дерево? - PullRequest
0 голосов
/ 16 апреля 2020

в моем коде ниже, я получаю входные данные из файла с числами в нем, которые нужно вставить в двоичное дерево. Однако во входном файле он содержит c слов, таких как «удалить 3» или «удалить 9». В коде, если число существует в дереве и оно достигает определенного ключевого слова c, такого как «удалить», оно удалит его. Однако, если номер не существует, и он достигает ключевого слова «удалить», он вместо этого вставит номер в дерево. Каждый раз, когда я запускаю его, я просто получаю ошибку переполнения стека, и она указывает на "String [] delete = key.toLowerCase (). Split (" ") и" leaf.setRight (insert (leaf.getRight (), key )); ".

Main

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Main
{
    public static void main(String[] args) throws FileNotFoundException
    {
        BinaryTree BT = new BinaryTree();
        Scanner input = new Scanner(new File("input.txt"));
        while(input.hasNextLine())
        {
            BT.insert(input.nextLine());
        }
        BT.inOrder();
    }
}

Двоичное дерево

public class BinaryTree
{
    Node root;
    String name;

    public void insert(String key) // recursion method to insert a name into the binary tree
    {
        root = insert(root, key);
    }

    public Node insert(Node leaf, String key) // recursion method
    {
        if (leaf == null) // if it is empty, make a new object
        {
            leaf = new Node(key);
        }

        String[] delete = key.toLowerCase().split(" ");

        if(delete[0].equals("delete"))
        {
            int value = Integer.parseInt(delete[1]);
            if(find(String.valueOf(value)))
            {
                leaf = deleteNode(leaf, value);
            }
            else // if input file has keyword delete, and it could not find it, make a new object
            {
                leaf = new Node(key);
            }
        }
        else if(Integer.parseInt(key) < Integer.parseInt(leaf.getKey())) // if the number is less than the root, place it on the left side
        {
            leaf.setLeft(insert(leaf.getLeft(), key));
        }
        else // otherwise, if its greater than the root place it on the right side
        {
            leaf.setRight(insert(leaf.getRight(), key));
        }
        return leaf;
    }

    public boolean find(String key) // checks to see if the duplicate name exists in the tree
    {
        Node curr = root;
        boolean found = false;
        while (!found) {
            if (curr == null) // if node is exhausted, leave the loop and return false
            {
                break;
            } else if (curr.getKey().equalsIgnoreCase(key)) // if node is exhausted, leave the loop and return true
            {
                found = true;
                break;
            } else if ((key.compareToIgnoreCase(curr.getKey())) < 0) // goes to the right side of the tree
            {
                curr = curr.getRight();
            } else // goes to the left side of the tree
            {
                curr = curr.getLeft();
            }
        }
        return found;
    }

    public Node deleteNode(Node leaf, int key)
    {
        if(leaf == null)
        {
            return null;
        }
        else if(key < Integer.parseInt(leaf.getKey())) // if the key is less than the current key, then go to the left side
        {
            leaf.setLeft(deleteNode(leaf.getLeft(), key));
        }
        else if(key > Integer.parseInt(leaf.getKey())) // if the key is greater than the current key, then go to the right side
        {
            leaf.setRight(deleteNode(leaf.getRight(), key));
        }
        else
        {
            if(leaf.getLeft() == null && leaf.getRight() == null) // no child case
            {
                return null;
            }
            else if(leaf.getRight() != null && leaf.getLeft() != null) // two children case
            {
                int value = minValue(leaf.getRight());
                leaf.setKey(String.valueOf(value));
                leaf.setRight(deleteNode(leaf.getRight(), key));
            }
            else // one child case
            {
                if(leaf.getLeft() != null)
                {
                    return leaf.getLeft();
                }
                else
                {
                    return leaf.getRight();
                }
            }
        }
        return leaf;
    }

    private int minValue(Node leaf)
    {
        return leaf.getLeft().getLeft() == null ? Integer.parseInt(leaf.getLeft().getKey()) : minValue(leaf.getLeft());
    }


    public Node findNode(String key)
    {
        boolean found = false;
        Node curr = root;
        while(!found)
        {
            if (curr == null) // if the binary tree is exhausted, it will no longer continue.
            {
                return null;
            }
            else if (curr.getKey().equalsIgnoreCase(key))
            {
                found = true; // if the name is found, it will stop the while loop.
            }
            else if ((key.compareToIgnoreCase(curr.getKey())) < 0) // if the key is smaller, it then traces to the right side of the root
            {
                curr = curr.getRight();
            }
            else // if the key is bigger, it will trace to the left side of the root it is in
            {
                curr = curr.getLeft();
            }
        }
        return curr;
    }

    public void postOrder()
    {
        Node curr = root;
        postOrder(curr);
    }

    public void postOrder(Node curr)
    {
        if(curr!=null)
        {
            postOrder(curr.getLeft());
            postOrder(curr.getRight());
            System.out.print(curr.getKey());
        }
    }

    public void preOrder()
    {
        Node curr = root;
        preOrder(curr);
    }

    public void preOrder(Node curr)
    {
        if(curr != null)
        {
            System.out.print(curr.getKey());
            preOrder(curr.getLeft());
            preOrder(curr.getRight());
        }
    }

    public void inOrder()
    {
        Node curr = root;
        preOrder(curr);
    }

    public void inOrder(Node curr)
    {
        if(curr != null)
        {
            inOrder(curr.getLeft());
            System.out.print(curr.getKey()+" ");
            inOrder(curr.getRight());
        }
    }
}

Узлы

public class Node
{
    String key;
    Node right; // used for the right side of a tree
    Node left; // uses for the left side of a tree

    Node(String key) // creates a node object with the name
    {
        this.key=key;
    }

    public String getKey() // returns the name of the leaf
    {
        return this.key;
    }

    public Node getRight() // gets the right side of the leaf
    {
        return this.right;
    }

    public void setRight(Node right) // points towards the right side of the leaf
    {
        this.right=right;
    }

    public void setLeft(Node left) // points towards the left side of the leaf
    {
        this.left=left;
    }

    public Node getLeft() // gets the left side of the leaf
    {
        return this.left;
    }
    public void setKey(String key)
    {
        this.key=key;
    }
}

input.txt

1
2
3
delete 3
5
6
delete 9
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...