問題:node
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.ide
Basically, the deletion can be divided into two stages:函數
Note: Time complexity should be O(height of tree).測試
Example:spa
root = [5,3,6,2,4,null,7] key = 3 5 / \ 3 6 / \ \ 2 4 7 Given key to delete is 3. So we find the node with value 3 and delete it. One valid answer is [5,4,6,2,null,null,7], shown in the following BST. 5 / \ 4 6 / \ 2 7 Another valid answer is [5,2,6,null,4,null,7]. 5 / \ 2 6 \ \ 4 7
解決:遞歸
【題意】rem
本題讓咱們刪除二叉搜索樹中的一個節點,難點在於刪除完節點並補上那個節點的位置後還應該是一棵二叉搜索樹。被刪除掉的節點位置,不必定是由其的左右子節點補上,好比下面這棵樹:it
7
/ \
4 8
/ \
2 6
\ /
3 5io若是咱們要刪除節點4,那麼應該將節點5補到4的位置,這樣才能保證仍是BST,那麼結果是以下這棵樹:class
7
/ \
5 8
/ \
2 6
\
3
① 遞歸方法解決:首先判斷根節點是否爲空。因爲BST的左<根<右的性質,使得咱們能夠快速定位到要刪除的節點,咱們對於當前節點值不等於key的狀況,根據大小關係對其左右子節點分別調用遞歸函數。若當前節點就是要刪除的節點,咱們首先判斷是否有一個子節點不存在,那麼咱們就將root指向另外一個節點,若是左右子節點都不存在,那麼root就賦值爲空了,也正確。難點就在於處理左右子節點都存在的狀況,咱們須要在右子樹找到最小值,即右子樹中最左下方的節點,而後將該最小值賦值給root,而後再在右子樹中調用遞歸函數來刪除這個值最小的節點。
class Solution { //8ms
public TreeNode deleteNode(TreeNode root, int key) {
if (root == null) return null;
if (root.val > key){
root.left = deleteNode(root.left,key);
}else if (root.val < key){
root.right = deleteNode(root.right,key);
}else {
if (root.left == null || root.right == null){
root = (root.left != null) ? root.left : root.right;
}else {
TreeNode cur = root.right;
while(cur.left != null){
cur = cur.left;
}
root.val = cur.val;
root.right = deleteNode(root.right,cur.val);
}
}
return root;
}
}
【注】有一個有問題的地方,上面的例子中,刪除3時,結果錯誤。。。多是測試的問題?
② 非遞歸方法解決。
class Solution { //8ms public TreeNode deleteNode(TreeNode root, int key) { TreeNode cur = root;//指向要刪除的節點 TreeNode pre = null;//指向要刪除節點的父節點 while(cur != null){ if (cur.val == key) break; pre = cur; if (cur.val > key){ cur = cur.left; }else { cur = cur.right; } } if (cur == null) return root; if (pre == null) return deleteNode(cur); if (pre.left != null && pre.left.val == key){ pre.left = deleteNode(cur); }else { pre.right = deleteNode(cur); } return root; } public TreeNode deleteNode(TreeNode node){ if (node.left == null && node.right == null) return null; if (node.left == null || node.right == null){ return node.left == null ? node.right : node.left; } TreeNode pre = node; TreeNode cur = node.right; while (cur.left != null){ pre = cur; cur = cur.left; } node.val = cur.val; if (pre == node){ node.right = cur.right; }else { pre.left = cur.right; } return node; } }