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). Example: 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
假設有一棵二叉搜索樹,如今要求從二叉搜索樹中刪除指定值,使得刪除後的結果依然是一棵二叉搜索樹。java
二叉搜索樹的特色是,對於樹中的任何一個節點,必定知足大於其全部左子節點值,小於全部其右子節點值。當刪除二叉搜索樹中的一個節點時,一共有三種場景:node
對每種狀況的圖例以下:ide
1. 葉節點 5 / \ 2 6 \ \ 4 7 (刪除4) 結果爲: 5 / \ 2 6 \ 7 2. 只有左子樹或是隻有右子樹 5 / \ 3 6 / \ \ 2 4 7(刪除6) 結果爲 5 / \ 3 6 / \ 2 4 3. 既有左子樹又有右子樹 6 / \ 3 7 / \ \ 2 5 8 (刪除6) / 4 首先找到6的左子樹中的最大值爲5,將5填充到6的位置 5 / \ 3 7 / \ \ 2 5 8 (刪除5) / 4 接着遞歸的在左子樹中刪除5,此時5知足只有一個子樹的場景,所以直接用子樹替換便可 5 / \ 3 7 / \ \ 2 4 8 (刪除5)
代碼以下:code
public TreeNode deleteNode(TreeNode cur, int key) { if(cur == null) return null; else if(cur.val == key) { if(cur.left != null && cur.right != null) { TreeNode left = cur.left; while(left.right != null) { left = left.right; } cur.val = left.val; cur.left = deleteNode(cur.left, left.val); }else if(cur.left != null) { return cur.left; }else if(cur.right != null){ return cur.right; }else { return null; } }else if(cur.val > key) { cur.left = deleteNode(cur.left, key); }else { cur.right = deleteNode(cur.right, key); } return cur; }