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),然后刪除属瓣。注意的是奕筐,對于刪除這類操作泪酱,要保留父節(jié)點(diǎn)
刪除:以被刪除元素為父節(jié)點(diǎn)的子樹,刪除其父節(jié)點(diǎn)娃殖。如果父節(jié)點(diǎn)下左右子樹都存在值戳,則選擇左子樹(可以任意選擇一個(gè)),選擇左子樹中最大的點(diǎn)。這個(gè)點(diǎn)可能是左子樹的根節(jié)點(diǎn)炉爆,一定是最右的節(jié)點(diǎn)堕虹。
找到該節(jié)點(diǎn)卧晓,將其值賦給父節(jié)點(diǎn)。然后刪除改節(jié)點(diǎn)赴捞。則若是子樹的父節(jié)點(diǎn)逼裆,則子樹的左子樹為根節(jié)點(diǎn)的左子樹,否則左子樹作為被刪除節(jié)點(diǎn)父節(jié)點(diǎn)的右子樹赦政。代替被刪除節(jié)點(diǎn)原來的位置
注意胜宇,最后一步,是要將左子樹賦值恢着,不是空指針桐愉。