2013-12-10 7 views
0

오직 하나의 항목 만 출력합니다. 바이너리 검색 트리 : 재귀 toString

public String toString() 
{ 
    return toString (_root); 
} 
private String toString(BSTnode root) 
{ 
    if (root == null) 
     return ""; 
    toString(root._left); 
    toString(root._right); 
    return root._data.toString(); 
} 

답변

3

어떻게 당신이 그들을 보여주고 싶은 않는 순서 오름차순으로 트리의 내용을 인쇄 할 생각입니까?

예를 들어 문자열을 추가해야합니다.

private String toString(BSTnode root) 
{ 
    StringBuilder builder = new StringBuilder(); 
    if (root == null) 
     return ""; 
    builder.append(toString(root._left)); 
    builder.append(toString(root._right)); 
    return builder.append(root._data.toString()).toString(); 
} 

또는 단지 문자열에 연결을 사용하십시오.

private String toString(BSTnode root) 
{ 
    String result = ""; 
    if (root == null) 
     return ""; 
    result += toString(root._left); 
    result += toString(root._right); 
    result += root._data.toString() 
    return result; 
} 
+0

신난다! 감사! – user2810123

0
//Helper 

public String toString(){ 
return "<" +toString(root) + ">"; 
} 

//recursively printing out the nodes 

public static String toString(Node r){ 
if(r==null) 
return ""; 
else 
return toString(r.left) + " " +r.value + " " +toString(r.right); 
} 
관련 문제