2013-03-06 164 views
0

我想使用按順序遍歷(在java中)打印出二叉樹,但沒有任何歧義。使用InOrder遍歷打印二叉樹沒有歧義

我從後訂單表示法輸入創建樹。

例如,input = 2 3 4 * - 5 + 然後,我創建樹,並希望使用按順序遍歷將其打印出來。

所以輸出必須是= 2 - (3 * 4)+ 5 但是,使用使用按順序遍歷顯然不會給我分隔括號。

我的問題是,我可以打印輸出我想要的方式,而不用幹涉基本的BinaryNode和BinaryTree類,但只改變我的驅動程序類?如果是這樣,我會如何去做這件事?

如果我只能做這個改變我的printInOrder方法(在BinaryNode類),這是什麼樣子至今:

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

這是我第一次堆棧溢出,去容易對如果我沒有正確發帖:)

回答

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 
     } 

    } 
}