2011-11-24 81 views
-2

這是我的方法到目前爲止它可能是錯誤的,但我需要在二叉樹中插入一個節點。在二叉樹中插入一個節點

public Node insert(Node node, int data) 
{ 
    if (root = null) 
    { 
     root = insert(data); 
    } 
    else if (data < node.data) 
    { 
     node.left = insert(data); 
    } 
    else if (data > node.data) 
    { 
     node.right = insert(data); 
    } 
} 

有幫助嗎?我正在使用bluej

+3

_「這可能是錯的」_不是一個好的問題描述。如果您有具體問題,請提問。如果您看到錯誤/異常(這很可能是這種情況),請將它們發佈。謝謝。 –

+0

如何在二叉樹中插入一個節點是我的問題 – Elliot678

回答

1

看看binary search tree上的維基百科頁面。 (由於你的節點是有序的,你實際上正在實現一個二叉查找樹)。

給出了每個常見操作 - 例如insertion - 。 Java代碼甚至提供並解釋。

0

我會做它:

public void insert(Node node, int data) 
{ 
    if (node == null) 
    { 
     node = new Node(data, null, null); // create a new leaf node with the data. 
    } 
    else if (data < node.data) 
    { 
     insert(node.left, data); 
    } 
    else if (data > node.data) 
    { 
     insert(node.right, data); 
    } 
} 

沒有必要在我看來任何回報,因爲你的樹已經連接,該功能只會在正確的位置添加一個新的節點。請撥打:

insert(root, data);