我想寫一個從二叉搜索樹中刪除節點的方法。BST刪除節點方法「切斷」樹的其餘部分
這是我的方法:
public void remove(Node node)
\t //Removes a given node and puts one of the nodes below it in its place until it reaches the end
\t {
\t \t
\t \t if (node.left != null) //If the node to the left is not empty
\t \t {
\t \t \t node.value = node.left.value; //Moves up the left node to take its place
\t \t \t remove(node.left); //Goes to the next node
\t \t \t if (node.left.right == null && node.left.left == null)
\t \t \t \t node.left = null; //Removes the last node at the end of the tree after moving it up
\t \t }
\t \t else if (node.right != null)
\t \t {
\t \t \t node.value = node.right.value; //Moves up the left node to take its place
\t \t \t remove(node.right); //Goes to the next node
\t \t \t if (node.right.left == null && node.right.right == null)
\t \t \t \t node.right = null; //Removes the last node at the end of the tree after moving it up
\t \t \t
\t \t } \t
\t \t
\t }
的問題是它只能在某些情況下。
比方說,比如我輸入60,70,65(根節點50) 樹看起來應該像
50
/\
60
/ \
70
/\
65
讓我們接着說,我選擇刪除60。這似乎是工作首先罰款。 但是,如果我然後運行我所信任的搜索方法,則返回70在其任何指針處都沒有節點。
我假設正在發生的是,70被設置爲null之前,65可以向上移動。由於技術上65不再連接到樹,所以搜索方法找不到它。
因此,像這樣:
50
/\
70
/ \
/\
65
的問題是,我不明白這到底是怎麼發生。特別是因爲它應該設置節點爲null,如果它的兩個指針指向空,由於if語句
if (node.left.right == null && node.left.left == null)
node.left = null;
和
if (node.right.left == null && node.right.right == null)
node.right = null;
而且,如果第一個if語句是不正確的(如果不!= null),不應該簡單地繼續「else」(並刪除正確的)insted?
任何建議或提示,非常歡迎。
請你幫個忙和BST代碼從Swing代碼分開。爲您的BST編寫單元測試並確保它正常工作,然後將其與前端連接起來。 –
我不知道如何在這裏製作一棵樹,但拿起原來的樹並把65放在60的地方。我不認爲有可能像你認爲你擁有一棵樹。 – Marichyasana
@Marichyasana例子的樹是一個正確的BST;那麼你修改後的結果就不是。 – Matt