Модераторы: LSD, AntonSaburov
  

Поиск:

Ответ в темуСоздание новой темы Создание опроса
> не выполняется условие для удаления 
V
    Опции темы
ArniLand
Дата 29.9.2010, 22:15 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Бывалый
*


Профиль
Группа: Участник
Сообщений: 227
Регистрация: 17.8.2008

Репутация: нет
Всего: нет



Удаление должно выполняться согласно следующему условию if (current.course == 3 && (current.month>=6 && current.month <=8)), иначе программа возвращает false, узел не удаляется и программа выводит на экран узлы дерева, выводит в таком же состояние какие они были  до момента вызова функции удаления. Но данное условие не выполняется, и не важно соответствуют данные условие или нет, при вызове указанный по ключу узел все равно удаляется. Подскажите, что я не так сделал.
 
Код программы:


Код

package tree_final;
public class BinaryTree {
    private  Node root;
    public BinaryTree()

    {  root = null;  }

     private void PrintRec(Node root) {
        if (root == null)
            return;
        root.Print();
        System.out.println();
        PrintRec(root.left);
        PrintRec(root.right);
    }
    public void Print(){
    PrintRec(root);
    return;
    }
    public void insert(int data, String name, String surname,
            int course, String ticket, int day, int month, int year ){

        Node n = new Node(data, name, surname, course, ticket, day, month, year);
        if (root == null){
            root = n;
        }
        else {
         Node current = root;
         Node parent;
         while(true) {
             parent = current;
             if(data < current.data){
                 current = current.left;
                }
                if (current == null) {
                    parent.left = n;
                    return;
                }
          else {
                current = current.right;
                if(current == null){
                    parent.right = n;
                    return;

                }
              }
           }
       }
    }



       public Node find(int key){
       Node current = root;

       while(current.data != key){
           if(key < current.data){
               current = current.left;
           }
           else {
                current = current.right;
           }

           if(current == null) {
               return null;
           }

       }
       return current;
    }
      public void inorderPrint(Node root) {
          if (root != null) {
              inorderPrint(root.left);
              System.out.println(root.data + "");
              inorderPrint(root.right);


          }
      }
      public void travers(){
          System.out.println("Inorder traversal");
          inorderPrint(root);
      }

      public boolean delete(int key) {

          Node current = root;
          Node parent = root;
          if (current.course == 3 && (current.month>=6 && current.month <=8)){ // условие
          boolean isLeft = true;
      
          while(current.data != key){
          parent = current;
          if (key <current.data) {
              isLeft = true;
              current = current.left;
          }
          else {
              isLeft = false;
              current = current.right;
          }
          if(current == null)
              return false;
      }
          if(current.left == null && current.right == null) {
              if(current == root)
                  root = null;
              else if(isLeft)
                  parent.left = null;
              else
                  parent.right = null;
              
          }
         
          else if(current.right==null)
              if(current==null)
                  root = current.left;
              else if(isLeft)
                  parent.left = current.left;
              else
                  parent.right = current.right;
          
          else if(current.left==null)
              if(current==root)
                  root = current.right;
              else if(isLeft)
                  parent.left = current.right;
              else
                  parent.right = current.right;
          
          else {
              Node successor = getSuccessor(current);
              if(current == root)
                  root = successor;
              else if(isLeft)
                  parent.left = successor;
              else
                  parent.right = successor;
              successor.left = current.left;
          }
          return true;
          }
          else
         return false;
      }



      private Node getSuccessor(Node delNode)
      {
      Node successorParent = delNode;
      Node successor = delNode;
      Node current = delNode.right;
      while(current != null)
         {
         successorParent = successor;
         successor = current;
         current = current.left;
         }

      if(successor != delNode.right)
         {
         successorParent.left = successor.right;
         successor.right = delNode.right;
         }
      return successor;
      }





    public static void main(String[] args ) {
        BinaryTree theTree = new BinaryTree();

        theTree.insert(1, "vasa", "pupkin", 3, "456987", 2, 7 , 1992);
        theTree.insert(2, "igor", "melnik", 2, "121545", 7, 1 , 1992);
        theTree.insert(3, "dima", "ladov", 2, "787999", 9, 3 , 1991);
        theTree.insert(4, "peta", "mishen", 3, "4477", 3, 8 , 1992);
        theTree.insert(5, "sasha", "ivanov", 2, "57878", 1, 5 , 1992);
        theTree.Print();

        theTree.travers();
        theTree.delete(2);
        theTree.Print();
        
        
        


        
        
        


 }
}
class Node {
        Node left;
        Node right;
        int data;
        String name;
        String surname;
        int course;
        String ticket;
        int day;
        int month;
        int year;
        public Node(int data, String name, String surname, int course, String ticket, int day, int month, int year){
            this.data = data;
            this.name = name;
            this.surname = surname;
            this.course = course;
            this.ticket = ticket;
            this.day = day;
            this.month = month;
            this.year = year;
        }
      public void Print(){
System.out.println("data" + data);
System.out.println("Имя" + name);
System.out.println("Фамилия" + surname);
System.out.println("Курс" + course);
System.out.println("День" + day);
System.out.println("месяц" + month);
System.out.println("год" + year);
}

}

Это сообщение отредактировал(а) ArniLand - 29.9.2010, 22:16
PM MAIL   Вверх
jk1
Дата 29.9.2010, 22:35 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Эксперт
***


Профиль
Группа: Участник
Сообщений: 1168
Регистрация: 17.10.2008
Где: Санкт-Петербург

Репутация: 40
Всего: 75



Переставьте условие:
Код

    public boolean delete(int key) {
        Node current = root;
        Node parent = root;

        boolean isLeft = true;

        while (current.data != key) {
            parent = current;
            if (key < current.data) {
                isLeft = true;
                current = current.left;
            } else {
                isLeft = false;
                current = current.right;
            }
            if (current == null)
                return false;
        }
        if (current.course == 3 && (current.month >= 6 && current.month <= 8)) { // условие
            if (current.left == null && current.right == null) {
                if (current == root)
                    root = null;
                else if (isLeft)
                    parent.left = null;
                else
                    parent.right = null;

            } else if (current.right == null)
                if (current == null)
                    root = current.left;
                else if (isLeft)
                    parent.left = current.left;
                else
                    parent.right = current.right;

            else if (current.left == null)
                if (current == root)
                    root = current.right;
                else if (isLeft)
                    parent.left = current.right;
                else
                    parent.right = current.right;

            else {
                Node successor = getSuccessor(current);
                if (current == root)
                    root = successor;
                else if (isLeft)
                    parent.left = successor;
                else
                    parent.right = successor;
                successor.left = current.left;
            }
            return true;
        } else
            return false;
    }



--------------------
Opinions are like assholes — everybody has one
PM MAIL   Вверх
  
Ответ в темуСоздание новой темы Создание опроса
Правила форума "Java"
LSD   AntonSaburov
powerOn   tux
javastic
  • Прежде, чем задать вопрос, прочтите это!
  • Книги по Java собираются здесь.
  • Документация и ресурсы по Java находятся здесь.
  • Используйте теги [code=java][/code] для подсветки кода. Используйтe чекбокс "транслит", если у Вас нет русских шрифтов.
  • Помечайте свой вопрос как решённый, если на него получен ответ. Ссылка "Пометить как решённый" находится над первым постом.
  • Действия модераторов можно обсудить здесь.
  • FAQ раздела лежит здесь.

Если Вам помогли, и атмосфера форума Вам понравилась, то заходите к нам чаще! С уважением, LSD, AntonSaburov, powerOn, tux, javastic.

 
0 Пользователей читают эту тему (0 Гостей и 0 Скрытых Пользователей)
0 Пользователей:
« Предыдущая тема | Java: Общие вопросы | Следующая тема »


 




[ Время генерации скрипта: 0.0465 ]   [ Использовано запросов: 22 ]   [ GZIP включён ]


Реклама на сайте     Информационное спонсорство

 
По вопросам размещения рекламы пишите на vladimir(sobaka)vingrad.ru
Отказ от ответственности     Powered by Invision Power Board(R) 1.3 © 2003  IPS, Inc.