二叉搜索樹(shù)的題目 GO語(yǔ)言實(shí)現(xiàn)

450.?Delete Node in a BST

Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return the root node reference (possibly updated) of the BST.

Basically, the deletion can be divided into two stages:

Search for a node to remove.

If the node is found, delete the node.

Note:?Time complexity should be O(height of tree).

首先找該節(jié)點(diǎn),然后刪除。注意的是,對(duì)于刪除這類(lèi)操作,要保留父節(jié)點(diǎn)

刪除:以被刪除元素為父節(jié)點(diǎn)的子樹(shù),刪除其父節(jié)點(diǎn)。如果父節(jié)點(diǎn)下左右子樹(shù)都存在,則選擇左子樹(shù)(可以任意選擇一個(gè)),選擇左子樹(shù)中最大的點(diǎn)。這個(gè)點(diǎn)可能是左子樹(shù)的根節(jié)點(diǎn),一定是最右的節(jié)點(diǎn)。

找到該節(jié)點(diǎn),將其值賦給父節(jié)點(diǎn)。然后刪除改節(jié)點(diǎn)。則若是子樹(shù)的父節(jié)點(diǎn),則子樹(shù)的左子樹(shù)為根節(jié)點(diǎn)的左子樹(shù),否則左子樹(shù)作為被刪除節(jié)點(diǎn)父節(jié)點(diǎn)的右子樹(shù)。代替被刪除節(jié)點(diǎn)原來(lái)的位置


注意,最后一步,是要將左子樹(shù)賦值,不是空指針。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容