2013-01-23 92 views
2
class Node { 
    Node parent; 
    Node left; 
    Node right; 
    int value; 

    Node (int value) { 
     this.value = value; 
     this.parent = null; 
     this.left = null; 
     this.right = null; 
    } 
} 

class TreeofNodes { 
    Node insert (Node root, Node node) { 
     if (root == null) 
     { 
      root = node; 
      return root; 
     } 

     Node cur = root; 
     Node father = root; 

     while(cur != null) 
     { 
      father = cur; 
      if (cur.value > node.value) 
       cur = cur.left; 
      else 
       cur = cur.right; 
     } 
     if(father.value > node.value) 
      father.left = node; 
     else 
      father.right = node; 

     node.parent = father; 

     return node; 
    } 

    void Inorder (Node n) { 
     if (n == null) 
      return; 
     Inorder (n.left); 
     System.out.print (n.value + " "); 
     Inorder (n.right); 
    } 
} 

class binarySearchTree { 

public static void main (String [] args) { 

    int A[] = {6, 8, 5, 3, 7, 9, 1}; 

    TreeofNodes obj = new TreeofNodes (); 

    Node root = null; 
    Node n = new Node (A[0]); 
    root = obj.insert (root, n); 

    Node Croot = root; 

    for (int i = 1; i < 7; i++) 
    { 
     n = new Node (A[i]); 
     Croot = obj.insert (Croot, n); 
    } 

    System.out.println ("============ Inorder ============"); 
    obj.Inorder (root); 
    } 
} 

當我打電話Inorder方法,我希望可以將輸出爲:序遍歷給不正確的輸出

1 3 5 6 7 8 9 

但它是

6 3 7 1 9 5 8 

我懷疑我的插入方法是錯誤的。

有人可以告訴我我錯在哪裏,我該如何解決?

回答

3

您的insert函數返回node而不是root。變化:

return node; 

return root; 
+0

謝謝你這麼多 –

+0

無需'insert'返回任何東西,真的。你可以在'新節點(A [0])之後立即將'Croot'設置爲'n',然後不改變它。你的根不應該在這種類型的二叉樹中改變。 –

+0

請寫下代碼 –