Delete Node in a BST (M)
題目
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
題意
洗掉二叉搜索樹中的一個結點,
思路
使用遞回實作:
- 如果 key<root.val,向左遞回;
- 如果 key>root.val,向右遞回;
- 如果 key==root.val,分為3中情況:
- root沒有左子樹,那么直接回傳root的右子樹;
- root沒有右子樹,那么直接回傳root的左子樹;
- root既有左子樹又有右子樹,那么在root的右子樹中找到最小的值,即右子樹中最左側的結點,將它的值賦給root,再刪掉這個結點(即上述沒有左子樹的情況),也可以找root左子樹中最大(最右側)的結點,
代碼實作
Java
class Solution {
public TreeNode deleteNode(TreeNode root, int key) {
if (root == null) {
return null;
}
if (key < root.val) {
root.left = deleteNode(root.left, key);
} else if (key > root.val) {
root.right = deleteNode(root.right, key);
} else if (root.left == null) {
root = root.right;
} else if (root.right == null) {
root = root.left;
} else {
TreeNode cur = root.right;
TreeNode pre = root;
while (cur.left != null) {
cur = cur.left;
pre = pre == root ? root.right : pre.left;
}
root.val = cur.val;
if (pre == root) {
pre.right = cur.right;
} else {
pre.left = cur.right;
}
}
return root;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/144284.html
標籤:其他
