2013-03-06 2 views
0

순 서적 순회를 사용하여 (Java로) 이진 트리를 인쇄하려하지만 모호성이 없습니다.모호함없이 InOrder 순회를 사용하여 이진 트리 인쇄하기

게시 주문 표기법 입력에서 트리를 만들었습니다.

예를 들어, 입력 = 2 3 4 * - 5 + 그런 다음 트리를 만들고 순서 순회를 사용하여 인쇄하려고합니다.

그래서 출력은 = 2 - (3 * 4) + 5 이어야합니다. 그러나 순차 탐색을 사용하면 분명히 분리 대괄호가 표시되지 않습니다.

제 질문은 기본 BinaryNode 및 BinaryTree 클래스에 간섭하지 않고 원하는대로 출력을 인쇄 할 수 있습니까? 내 드라이버 클래스 만 변경합니까? 그렇다면 어떻게해야할까요?

public void printInOrder() 
    { 
     if (left != null) 
     { 
      left.printInOrder();   // Left 
     } 
     System.out.print(element);  // Node 
     if (right != null) 
     { 
      right.printInOrder();   // Right 
     } 
    } 

이 스택 오버플로 내 처음이다, 쉽게 갈 : 만합니다 (BinaryNode 클래스) 내 printInOrder 방법을 변경하여이 작업을 수행 할 수있는 경우

이는 지금까지 모습입니다 만약 내가 올바르게 게시하지 않았다면 :

답변

0

예를 들어, 23 + 4 + 5 *의 입력은 ((2 + 3) +4) * 5)

아래 코드 참조 :

//NOTE: printInOrder has been modified to exclude ambiguity 
public void printInOrder() 
{ 
    if (left != null) 
    { 
     if (height(left)== 0) 
     { 
      //when we reache the bottom of a node, we put a bracket around each side as we know this will have it's own operation 
      // eg: * 
      // /\ 
      // 3 4 
      System.out.print("("); 
      left.printInOrder();   // Left 
     } 
     else 
     { 
      // We also put in a bracket here as this matches the closing brackets to come (which we do not know about yet) 
      System.out.print("("); 
      left.printInOrder();   // Left 
     } 

    } 
     System.out.print(element);    // Node 
    if (right != null) 
    { 
     if (height(right) == 0) 
     { 
      //when we reache the bottom of a node, we put a bracket around each side as we know this will have it's own operation 
      // eg: * 
      // /\ 
      // 3 4 
      right.printInOrder();   // Right 
      System.out.print(")"); 
     } 
     else 
     { 
      right.printInOrder();   // Right 
      // System.out.print(")"); // this print statement actually isnt necessary 
     } 

    } 
} 
관련 문제