2017-11-26 3 views
1

다음 클래스가 있고 정수를 사용하여 BST를 만들지, 문자열을 사용하여 BST를 만들지 사용자가 선택하도록하고 싶습니다. 사용자가 5를 선택할 때 정수에서 BST를 만들거나 6을 누를 때 문자열에서 BST를 만들려면 어떻게해야합니까? 또한 누군가가 내 제네릭 pls에 뭔가 잘못 찾으면 알려줘! 나는에 캐릭터 (사용자 입력)을 처리하는 방법을 추가 할 수이진 검색 트리 일반

이 내 제안

덕분에 많은 코드에서 제네릭을 최대한 활용하기 위해

public class BSTNode <T extends Comparable<T>> 
{ 
     T value; 
     BSTNode<T> left; 
     BSTNode<T> right; 

     public BSTNode(T value, BSTNode<T> l,BSTNode<T> r) 
     { 
      this.value = value; 
      left = l; 
      right = r; 
     } 

     public BSTNode(T value) 
     { 
      this(value,null,null); 
     } 

     public T getValue() 
     { 
      return value; 
     } 

     public void setValue(T value) 
     { 
      this.value = value; 
     } 

     public BSTNode<T> getLeftChild() 
     { 
      return left; 
     } 

     public BSTNode<T> getRightChild() 
     { 
      return right; 
     } 

     public void setLeftChild(BSTNode<T> node) 
     { 
      left = node; 
     } 

     public void setRightChild(BSTNode<T> node) 
     { 
      right = node; 
     } 

     public boolean search(T value) 
     { 
      if (value.equals(this.value)) 
        return true; 
      else if (value.compareTo(this.value) < 0) 
      { 
        if (left == null) 
         return false; 
        else 
         return left.search(value); 
      } else if (value.compareTo(this.value) > 0) 
      { 
        if (right == null) 
         return false; 
        else 
         return right.search(value); 
      } 
      return false; 
     } 

     public boolean add(T value) 
     { 
      if (value.compareTo(this.value)==0) 
        return false; 
      else if (value.compareTo(this.value) < 0) 
      { 
        if (left == null) 
        { 
         left = new BSTNode<T>(value); 
         return true; 
        } else 
         return left.add(value); 
      } 
      else if (value.compareTo(this.value) > 0) 
      { 
        if (right == null) 
        { 
         right = new BSTNode<T>(value); 
         return true; 
        } 
        else 
         return right.add(value); 
      } 
      return false; 
     } 



    public boolean remove(T value2, BSTNode<T> parent) 
     { 
     if (value2.compareTo(this.value)<0) 
     { 
      if (left != null) 
       return left.remove(value2, this); 
      else 
       return false; 
     } 
     else if (value2.compareTo(this.value)>0) 
     { 
      if (right != null) 
       return right.remove(value2, this); 
      else 
       return false; 
     } 
     else 
     { 
      if (left != null && right != null) 
      { 
       this.value = right.minValue(); 
       right.remove(this.value, this); 
      } 
      else if (parent.left == this) 
      { 
       parent.left = (left != null) ? left : right; 
      } 
      else if (parent.right == this) 
      { 
       parent.right = (left != null) ? left : right; 
      } 
      return true; 
     } 
    } 

    public T minValue() 
    { 
     if (left == null) 
      return value; 
     else 
      return left.minValue(); 
    } 

} 

    public class BinarySearchTree <T extends Comparable<T>> 
{ 
     private BSTNode<T> root; 

     public BinarySearchTree(T value) 
     { 
      root = new BSTNode<T>(value); 
     } 


     public BSTNode getRoot() 
     { 
      return root; 
     } 

     public boolean search(T value) 
     { 
      if (root.equals(null)) 
       return false; 
     else 
       return root.search(value); 
    } 

     public boolean add(T value) 
     { 
      if (root == null) { 
       root = new BSTNode(value); 
       return true; 
     } else 
       return root.add(value); 
     } 

     public boolean remove(T value) { 
      if (root == null) 
       return false; 
      else { 
       if (root.getValue() == value) { 
        BSTNode auxRoot = new BSTNode(null); 
        auxRoot.setLeftChild(root); 
        boolean result = root.remove(value, auxRoot); 
        root = auxRoot.getLeftChild(); 
        return result; 
       } else { 
        return root.remove(value, null); 
       } 
      } 
      } 

    public static void displayInorder(BSTNode T) 
     { 
      if (T!=null) 
      { 
       if (T.getLeftChild()!=null) 
       {    
        displayInorder(T.getLeftChild());    
       } 
       System.out.print(T.getValue() + " "); 
       if(T.getRightChild()!=null) 
       { 
        displayInorder(T.getRightChild()); 
       } 
      } 

     } 
    } 

import java.util.Scanner; 

public class main { 
    public static void main(String[] args) { 
     BinarySearchTree b = new BinarySearchTree(null); 
     boolean flag = true; 
     while (flag) { 
     Scanner scan = new Scanner(System.in); 
      System.out.println("Select 1 to add values in to BST\n" 
       + "Select 2 to delete values from the BST \n" 
       + "Select 3 to search for a value\n" 
       + "Select 4 to display te values held in the BST\n" 
       + "Select 5 to create a BST of strings\n" 
       + "Select 6 to create a BST of integers\n" 
       + "Select 7 to exit"); 
      int opt = scan.nextInt(); 

    switch (opt) { 
    case 1: System.out.println("Insert the value of your choice: "); 
      String str = scan.next(); 
      b.add(str); 
      break; 
    case 2: System.out.println("Insert the value of your choice: "); 
       str = scan.next(); 
       b.remove(str); 
      break; 
    case 3: 
     System.out.println("Insert the value of your choice: "); 
      str = scan.next(); 
      b.search(str); 
     break; 
    case 4: 
     BinarySearchTree.displayInorder(b.getRoot()); 
     break; 
    case 5: 

    case 7: 
     flag=false; 
     break; 
    } 
    } 
} 
} 

답변

0

입니다 트리 클래스의 적절한 유형 :

... 
import java.util.function.Function; 
... 

public class BinarySearchTree <T extends Comparable<T>> 
{ 
     private BSTNode<T> root; 
     private Function<String,T> valueDecoder 

     public BinarySearchTree(final Function<String,T> valueDecoder) 
     { 
      this.valueDecoder = valueDecoder; 
      root = new BSTNode<T>(null); 
     } 

     ... 
     public boolean decodeAndAdd(final String encodedValue) { 
      return add(valueDecoder.apply(encodedValue)); 
     } 

     public boolean decodeAndRemove(final String encodedValue) { 
      return remove(valueDecoder.apply(encodedValue)); 
     } 
} 

```다음

는 것 b 변수를 undefined/null로 남겨 두십시오. 실제로 사용자가 제공 한 선택 항목이있는 트리 유형이 표시됩니다. 이 여기 String 또는 Integer을 포함 할 수 있기 때문에 그 제약 조건의 일부로서 만 ?이 경우에 괜찮 ..., 유형 매개 변수로 아마 ? extends Comparable<?>?를 사용할 수 있습니다

BinarySearchTree<?> b = null; 사용자는 실제 요소 값으로 스캔 한 문자열을 전송하는 적절한 람다 제공 할 필요가 String 또는 Integer 나무를 요청할 때

지금 : 추가 이제

case 5: 
    b = new BinarySearchTree<>(scanStr -> scanStr); 
    break; 
case 6: 
    b = new BinarySearchTree<>(scanStr -> Integer.parseInt(scanStr)); 
    break; 

를 제거 사소한 있습니다 :

case 1: 
    b.decodeAndAdd(scan.next()); 
    break; 

case 2: 
    b.decodeAndRemove(scan.next()); 
    break; 

트리가 Integer 트리 인 경우 올바르지 않은 정수 문자열 값을 제공하면 NumberFormatException이되고 프로그램이 중지됩니다. 아마도 오히려 오류 메시지를 표시하고 사용자가 다른 운영자를 수행하게 할 수도 있습니다. 이를 위해 :

case 6: 
    b = new BinarySearchTree<>(scanStr -> { 
     try { 
      return Integer.parseInt(scanStr); 
     } catch (NumberFormatException ex) { 
      throw new IllegalArgumentException("you must provide a valid integer value: '" + scanStr + "'"); 
     } 
    }); 
    break; 
... 

case 1: 
    try { 
     b.decodeAndAdd(scan.next()); 
    } catch (final IllegalArgumentException ex) { 
     System.err.println("ERROR: " + ex.getMessage()); 
    } 
    break; 

case 2: 
    try { 
     b.decodeAndRemove(scan.next()); 
    } catch (final IllegalArgumentException ex) { 
     System.err.println("ERROR: " + ex.getMessage()); 
    } 
    break; 

아마도 당신은 BST 질문에 설명 된 사용자 명령 줄 컨텍스트 외부에서 사용될 수있는 사물을 좀 더 모듈을 유지하려는 경우 BinarySearchTree 클래스에 decodeAndAdd 및 decodeAndRemove를 추가하는 적합하지 않습니다.

그런 경우 유형 매개 변수를 사용하여 동일하게 바인딩 된 요소 유형의 BST 및 디코딩 람다에 대한 참조를 포함하는 참조를 포함하는 클래스와 같은 일반 "구조체"를 정의 할 수 있습니다.

class CommandLineBST<T> { 

    public final BST<T> tree; 
    public final Function<String, T> valueDecoder; 

    public CommandLineBST(final BST<T> tree, final Function<String, T> decoder) { 
     this.tree = tree; 
     this.valueDecoder = decoder; 
    } 

    public boolean add(final String scanStr) { 
    return tree.add(valueDecoder.apply(scanStr)); 
    } 

    public boolean remove(final String scanStr) { 
    return tree.remove(valueDecoder.apply(scanStr)); 
    } 

} 

또는

class CommandLineBST<T> extends BST<T> { 
    private Function<String, T> valueDecoder; 

    public CommandLineBST(final Function<String, T> valueDecoder) { 
     super(null); 
     this.valueDecoder = valueDecoder; 
    } 

    public boolean decodeAndAdd(final String scanStr) { ... } 
    public boolean decodeAndRemove(final String scanStr) { ... } 
} 
: 당신은 또한이 기능을 추가 다른 사용자 인터페이스 전문 BST의 BST 클래스를 확장 할 수