2013-08-09 3 views
1

이진 검색 트리를 사용하여 Set 제네릭을 구현하는 클래스를 만듭니다. 나는 내 toString() 메서드를 구현하여 소괄호 표현을 표시하지만 작동하도록하는 데 문제가 있습니다.toString() 메서드 및 재귀 호출

enter image description here

내가 같은 출력이 이진 트리를 내 toString 메서드를 원할 것 : 예를 들어, 여기에 기본 이진 트리입니다 () 빈 나무를 의미

(10 (5 (4()()) (6()())) (20 (15()()) (25()()))) 

.

다음은 toString 메소드를 사용하는 클래스입니다. 어떤 도움을 주셔서 감사합니다!

// Allow short name access to following classes 
import csc143.data_structures.*; 

public class MySet<E> implements SimpleSet<E> { 

    // the root of the "tree" that structures the set 
    private BTNode root; 
    // the current number of elements in the set 
    private int numElems; 

    public MySet() { 
    root = null; 

    numElems = 0; 
    } 

    /** 
    * Add an element to the set. 
    * 
    * @param e The element to be added to the set. 
    * @return <tt>true</tt> If this operation updated the contents of the set. 
    */ 
    public boolean add(E e) { 
    try { 
     root = addToSubtree(root, (Comparable) e); 
     return true; 
    } catch(DuplicateAdded exc) { 
     // duplicate trying to be added 
     return false; 
    } 

    } 

    // This helper method adds the element "e" to tree rooted at r. Returns 
    // (possibly new) tree containing "e", or throws DuplicateAdded exception 
    // if "e" already exists in tree. 
    private BTNode addToSubtree(BTNode r, Comparable elem) 
    throws DuplicateAdded { 
    if(r == null) { 
     numElems++; 
     return new BTNode(elem); 
    } 

    int compare = elem.compareTo(r.item); 
    // element already in tree 
    if(compare == 0) { 
     throw new DuplicateAdded(); 
    } else if(compare < 0) { 
     r.left = addToSubtree(r.left, elem); 
    } else { // compare > 0 
     r.right = addToSubtree(r.right, elem); 
    } 

    // element has been added 
    return r; 
    } 

    /** 
    * Remove all elements from this set. 
    */ 
    public void clear() { 
    root = null; 

    numElems = 0; 
    } 

    /** 
    * Checks for the existance of the specified value within the set. 
    * 
    * @param e The value sought. 
    * @return <tt>true</tt> If the value exists in the set. 
    */ 
    public boolean contains(E e) { 
    return subtreeContains(root, (Comparable) e); 
    } 

    // This helper method returns whether element "elem" is in 
    // (sub-)tree with root "r". 
    private boolean subtreeContains(BTNode r, Comparable elem) { 
    if(r == null) { 
     return false; 
    } else { 
     int compare = elem.compareTo(r.item); 
     // found element 
     if(compare == 0){ 
     return true; 
     } else if(compare < 0) { 
     return subtreeContains(r.left, elem); 
     } else { // compare > 0 
     return subtreeContains(r.right, elem); 
     } 

    } 

    } 

    /** 
    * Check for the existance of elements in the set. 
    * 
    * @return <tt>true</tt> If there are no elements in the set. 
    */ 
    public boolean isEmpty() { 
    return root == null; 
    } 

    /** 
    * Return the number of elements in the set. 
    * 
    * @return The number of elements in the set. 
    */ 
    public int size() { 
    return numElems; 
    } 

    /** 
    * Returns a String representation of the contents of the set. 
    * 
    * @return The String representation of the set. 
    */ 
    public String toString() { 
    return subtreeToString(root); 
    } 

    private String subtreeToString(BTNode r) { 
    String str = ""; 
    if(r == null) { 
     str += "() "; 
     return str; 
    } 

    str += "(" + r.item; 
    str += subtreeToString(r.left) + 
     subtreeToString(r.right) + ")"; 

    return str; 
    } 

    // this inner class creates the node that compose the binary tree structure 
    class BTNode<E> { 

    /** 
    * The item stored in the node. 
    */ 
    public E item; 

    /** 
    * The node to the left of "this" node. 
    */ 
    public BTNode left; 

    /** 
    * The node to the right of "this" node. 
    */ 
    public BTNode right; 

    /** 
    * Constructs the BTNode object (three parameters). 
    * 
    * @param item The item to be stored in the node. 
    * @param left The node to the left of "this" node. 
    * @param right The node to the right of "this" node. 
    */ 
    @SuppressWarnings("unchecked") 
    public BTNode(Object item, BTNode left, BTNode right) { 
     // bind to references 
     this.item = (E) item; 
     this.left = left; 
     this.right = right; 
    } 

    /** 
    * Constructs the BTNode (one parameter). 
    * 
    * @param The item to be stored in the node. 
    */ 
    public BTNode(Object item) { 
     // call three parameter constructor 
     this(item, null, null); 
    } 

    } 

} 

답변

0

는 내가 코드를 실행하려고 할 때 몇 가지 문제로 실행하지만, 모든 문제가 해결된다고 가정 - (가) 나를 위해 일한 다음 :

private String subtreeToString(BTNode r) { 
    String str = ""; 
    if(r == null) { 
     return str; 
    } 
    str += r.item; 
    str += " (" + subtreeToString(r.left) + ") (" + subtreeToString(r.right) + ")"; 
    return str; 
} 

출력 :

10 (5 (4()()) (6()())) (20() (25()())) 

(위에 제공된 예제 출력에 실수가 있습니다. 닫음 괄호는 6의 자식 뒤에 추가해야합니다)

+0

고마워, 그냥 고쳐. – adub3

+0

정수 1과 2를 더할 때'(1() (2()()))'를 얻어야합니다. 그러나, 나는'1 (()) (2 (()))'(''))'... – adub3

+0

을 받았다.'r'이 null 일 때'')'를 반환한다. 내 구현을 다시 확인하십시오. 루트 앞에 여는 대괄호를 사용하지 않아야합니다. 원하는 경우 내 구현을 : str + = r.item;에서 : str + = "("+ r.item; str + = "("+ subtreeToString (r.left) + ")로 변경해야합니다. ("+ subtreeToString (r.right) +")) "; ' – alfasin