2014-07-23 2 views
0

나는 다음과 같은 출력 이진 검색 트리를 인쇄 얻기 위해 노력하고 있어요 :인쇄 BST 형식화 된 출력

-19-> 4 -> 5> 6> 259->

어떻게 조정 할을 마지막 화살표가 출력에 인쇄되지 않도록 가로 지르는 기능?

내가 메인 함수 내에서이 코드를 사용하고 있습니다 :

Tree x = new Tree(5); 
x.add(6); 
x.add(4); 
x.add(259); 
x.add(-19); 
x.traverse(x); 

트리 클래스는 다음과 같습니다 :

public class Tree { 
    Tree root; 
    Tree left; 
    Tree right; 
    int value; 

public Tree(int value){ 
    this.value=value; 
    this.left=null; 
    this.right=null; 
} 

boolean add(int value){ 

    if (value == this.value) 
     return false; 
    else if (value <this.value) { 
     if (left == null) { 
      left = new Tree(value); 
      return true; 
     } else 
      return left.add(value); 
    } else if (value > this.value) { 
     if (right == null) { 
      right = new Tree(value); 
      return true; 
     } else 
      return right.add(value); 
    } 
    return false; 

} 

void traverse(Tree root){ 

    if (root.left != null){ 
     traverse(root.left); 
    }  

    System.out.printf("%d",root.value); 
    System.out.printf("->"); 
    if (root.right != null){ 
     traverse(root.right); 
    } 
} 
} 
+0

이다 -1945-> 6-> 259 – Rajan

답변

0

당신은, 마지막의 -> 인쇄를 피하려고 즉, 가장 큰, 요소. 따라서 노드에 올바른 하위 노드가없고 그 노드로 연결되는 모든 노드가 "올바른"노드 인 경우에는 인쇄하지 않으려합니다.

void traverse(Tree root, boolean allRight){ 

    if (root.left != null){ 
     traverse(root.left, false); 
    }  

    System.out.printf("%d",root.value); 
    if(!allRight || root.right != null) 
     System.out.printf("->"); 
    if (root.right != null){ 
     traverse(root.right, allRight); 
    } 
} 

또한 이제는 x.traverse(x, true)이라고 부릅니다.

+0

출력은 이제 -1945->> 259 – Rajan

+0

6- 그것을 고정 user40680 희망 @. – Pradhan

+0

두 번째 트래버스하는 재귀 호출의 두 번째 매개 변수는 true입니다. 그게 고칠 고마워! – Rajan

0

여기서 출력 지금 다른 버전

public boolean traverse(TreeNode root){ 

    if (root.left != null){ 
     traverse(root.left); 
     System.out.printf("->"); 

    }  

    System.out.printf("%d",root.value); 

    if (root.right != null){ 
     System.out.printf("->"); 
     traverse(root.right);   
    } 

    return true; 
}