2017-06-05 16 views
-1

我寫了二叉樹數據結構中的前序和中序遍歷的代碼,但預序遍歷的結果是正確的,但我得到了一些錯誤inorder遍歷,任何人都可以在我的代碼中顯示我的錯誤。 在此先感謝。無法得到正確的結果,在二叉樹中的inorder遍歷,Java數據結構

public class treepractice { 
static Node root = null; 

static class Node{ 
    int data; 
    Node left, right; 
    Node(int d){ 
     data = d; 
     left=right = null; 
    } 
} 

public static void main(String[] agrs){ 
    treepractice tree = new treepractice(); 
    tree.root = new Node(1); 
    tree.root.left = new Node(2); 
    tree.root.right = new Node(3); 
    tree.root.left.left = new Node(4); 
    tree.root.left.right = new Node(5); 
// root.right.left = new Node(6); 

    tree.printInorder(root); 
    System.out.println(); 
    tree.printPreorder(root); 
    System.out.println(); 

} 



private static void printPreorder(Node root) { 
    if(root == null) 
     return; 
     System.out.print(root.data + " "); 
     printPreorder(root.left); 
     printPreorder(root.right); 
} 

private static void printInorder(Node root) { 
    if(root == null) 
     return; 
     printPreorder(root.left); 
     System.out.print(root.data + " "); 
     printPreorder(root.right); 
} 
} 
+0

請求調試幫助不適合Stack Overflow問題。如果您對代碼的特定功能有特定問題,請使用這些詳細信息編輯您的問題。另外,不管你發佈這樣的問題在哪裏,不要只說「有些錯誤」。始終給出確切的錯誤代碼,錯誤文本或有問題行爲的詳細說明。 –

回答

1

要調用從printInorderprintPreorder方法,你必須調用printInorder

private static void printInorder(Node root) { 
    if (root == null) 
     return; 
    printInorder(root.left); 
    System.out.print(root.data + " "); 
    printInorder(root.right); 
} 
0

在你的代碼printInorder方法應該調用遞歸同樣的方法

private static void printInorder(Node root) { 
      if (root == null) 
       return; 
      printInorder(root.left); 
      System.out.print(root.data + " "); 
      printInorder(root.right); 
     }