|
| 1 | + |
| 2 | + |
| 3 | +<!-- problem:start --> |
| 4 | + |
| 5 | +# [450. Delete Node in a BST](https://leetcode.com/problems/delete-node-in-a-bst) |
| 6 | + |
| 7 | + |
| 8 | +- **comments**: true |
| 9 | +- **difficulty**: Medium |
| 10 | +- **tags**: |
| 11 | + - Tree |
| 12 | + - Binary Search Tree |
| 13 | + - Binary Tree |
| 14 | + |
| 15 | +## Description |
| 16 | + |
| 17 | +<p>Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return <em>the <strong>root node reference</strong> (possibly updated) of the BST</em>.</p> |
| 18 | + |
| 19 | +<p>The deletion can be divided into two stages:</p> |
| 20 | +<ol> |
| 21 | + <li>Search for a node to remove.</li> |
| 22 | + <li>If the node is found, delete the node.</li> |
| 23 | +</ol> |
| 24 | + |
| 25 | +### Example 1: |
| 26 | +<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0450.Delete%20Node%20in%20a%20BST/images/del_node_1.jpg" style="width: 800px; height: 214px;" /> |
| 27 | + |
| 28 | +<pre> |
| 29 | +<strong>Input:</strong> root = [5,3,6,2,4,null,7], key = 3 |
| 30 | +<strong>Output:</strong> [5,4,6,2,null,null,7] |
| 31 | +<strong>Explanation:</strong> Given key to delete is 3. So we find the node with value 3 and delete it. |
| 32 | +One valid answer is [5,4,6,2,null,null,7], shown in the above BST. |
| 33 | +Another valid answer is [5,2,6,null,4,null,7]. |
| 34 | +<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0450.Delete%20Node%20in%20a%20BST/images/del_node_supp.jpg" style="width: 350px; height: 255px;" /> |
| 35 | +</pre> |
| 36 | + |
| 37 | +### Example 2: |
| 38 | + |
| 39 | +<pre> |
| 40 | +<strong>Input:</strong> root = [5,3,6,2,4,null,7], key = 0 |
| 41 | +<strong>Output:</strong> [5,3,6,2,4,null,7] |
| 42 | +<strong>Explanation:</strong> The tree does not contain a node with value = 0. |
| 43 | +</pre> |
| 44 | + |
| 45 | +### Example 3: |
| 46 | + |
| 47 | +<pre> |
| 48 | +<strong>Input:</strong> root = [], key = 0 |
| 49 | +<strong>Output:</strong> [] |
| 50 | +</pre> |
| 51 | + |
| 52 | +## Constraints: |
| 53 | + |
| 54 | +- The number of nodes in the tree is in the range <code>[0, 10<sup>4</sup>]</code>. |
| 55 | +- <code>-10<sup>5</sup> <= Node.val <= 10<sup>5</sup></code> |
| 56 | +- Each node has a <strong>unique</strong> value. |
| 57 | +- <code>root</code> is a valid binary search tree. |
| 58 | +- <code>-10<sup>5</sup> <= key <= 10<sup>5</sup></code> |
| 59 | + |
| 60 | +**Follow up:** Could you solve it with time complexity <code>O(height of tree)</code>? |
| 61 | + |
| 62 | +<!-- problem:end --> |
| 63 | + |
| 64 | +## Solutions |
| 65 | + |
| 66 | +<!-- solution:start --> |
| 67 | + |
| 68 | +### Solution 1 |
| 69 | + |
| 70 | +<!-- tabs:start --> |
| 71 | + |
| 72 | +#### 🐍 Python3 |
| 73 | + |
| 74 | +```python |
| 75 | +# Definition for a binary tree node. |
| 76 | +# class TreeNode: |
| 77 | +# def __init__(self, val=0, left=None, right=None): |
| 78 | +# self.val = val |
| 79 | +# self.left = left |
| 80 | +# self.right = right |
| 81 | +class Solution: |
| 82 | + def deleteNode(self, root: Optional[TreeNode], key: int) -> Optional[TreeNode]: |
| 83 | + if root is None: |
| 84 | + return None |
| 85 | + if key < root.val: |
| 86 | + root.left = self.deleteNode(root.left, key) |
| 87 | + elif key > root.val: |
| 88 | + root.right = self.deleteNode(root.right, key) |
| 89 | + else: |
| 90 | + if not root.left: |
| 91 | + return root.right |
| 92 | + elif not root.right: |
| 93 | + return root.left |
| 94 | + # Find the inorder successor (smallest in the right subtree) |
| 95 | + temp = root.right |
| 96 | + while temp.left: |
| 97 | + temp = temp.left |
| 98 | + root.val = temp.val |
| 99 | + root.right = self.deleteNode(root.right, temp.val) |
| 100 | + return root |
| 101 | +``` |
| 102 | + |
| 103 | +#### ☕ Java |
| 104 | + |
| 105 | +```java |
| 106 | +class Solution { |
| 107 | + public TreeNode deleteNode(TreeNode root, int key) { |
| 108 | + if (root == null) return null; |
| 109 | + if (key < root.val) { |
| 110 | + root.left = deleteNode(root.left, key); |
| 111 | + } else if (key > root.val) { |
| 112 | + root.right = deleteNode(root.right, key); |
| 113 | + } else { |
| 114 | + if (root.left == null) return root.right; |
| 115 | + if (root.right == null) return root.left; |
| 116 | + TreeNode minNode = getMin(root.right); |
| 117 | + root.val = minNode.val; |
| 118 | + root.right = deleteNode(root.right, root.val); |
| 119 | + } |
| 120 | + return root; |
| 121 | + } |
| 122 | + |
| 123 | + private TreeNode getMin(TreeNode node) { |
| 124 | + while (node.left != null) node = node.left; |
| 125 | + return node; |
| 126 | + } |
| 127 | +} |
| 128 | +``` |
| 129 | + |
| 130 | +#### 💻 C++ |
| 131 | + |
| 132 | +```cpp |
| 133 | +class Solution { |
| 134 | +public: |
| 135 | + TreeNode* deleteNode(TreeNode* root, int key) { |
| 136 | + if (!root) return nullptr; |
| 137 | + if (key < root->val) { |
| 138 | + root->left = deleteNode(root->left, key); |
| 139 | + } else if (key > root->val) { |
| 140 | + root->right = deleteNode(root->right, key); |
| 141 | + } else { |
| 142 | + if (!root->left) return root->right; |
| 143 | + if (!root->right) return root->left; |
| 144 | + TreeNode* minNode = getMin(root->right); |
| 145 | + root->val = minNode->val; |
| 146 | + root->right = deleteNode(root->right, root->val); |
| 147 | + } |
| 148 | + return root; |
| 149 | + } |
| 150 | + |
| 151 | + TreeNode* getMin(TreeNode* node) { |
| 152 | + while (node->left) node = node->left; |
| 153 | + return node; |
| 154 | + } |
| 155 | +}; |
| 156 | +``` |
| 157 | + |
| 158 | +#### 🌀 Go |
| 159 | + |
| 160 | +```go |
| 161 | +func deleteNode(root *TreeNode, key int) *TreeNode { |
| 162 | + if root == nil { |
| 163 | + return nil |
| 164 | + } |
| 165 | + if key < root.Val { |
| 166 | + root.Left = deleteNode(root.Left, key) |
| 167 | + } else if key > root.Val { |
| 168 | + root.Right = deleteNode(root.Right, key) |
| 169 | + } else { |
| 170 | + if root.Left == nil { |
| 171 | + return root.Right |
| 172 | + } |
| 173 | + if root.Right == nil { |
| 174 | + return root.Left |
| 175 | + } |
| 176 | + minNode := getMin(root.Right) |
| 177 | + root.Val = minNode.Val |
| 178 | + root.Right = deleteNode(root.Right, root.Val) |
| 179 | + } |
| 180 | + return root |
| 181 | +} |
| 182 | + |
| 183 | +func getMin(node *TreeNode) *TreeNode { |
| 184 | + for node.Left != nil { |
| 185 | + node = node.Left |
| 186 | + } |
| 187 | + return node |
| 188 | +} |
| 189 | +``` |
| 190 | + |
| 191 | +#### 💠 TypeScript |
| 192 | + |
| 193 | +```ts |
| 194 | +function deleteNode(root: TreeNode | null, key: number): TreeNode | null { |
| 195 | + if (!root) return null; |
| 196 | + if (key < root.val) { |
| 197 | + root.left = deleteNode(root.left, key); |
| 198 | + } else if (key > root.val) { |
| 199 | + root.right = deleteNode(root.right, key); |
| 200 | + } else { |
| 201 | + if (!root.left) return root.right; |
| 202 | + if (!root.right) return root.left; |
| 203 | + const minNode = getMin(root.right); |
| 204 | + root.val = minNode.val; |
| 205 | + root.right = deleteNode(root.right, minNode.val); |
| 206 | + } |
| 207 | + return root; |
| 208 | +} |
| 209 | + |
| 210 | +function getMin(node: TreeNode): TreeNode { |
| 211 | + while (node.left) node = node.left; |
| 212 | + return node; |
| 213 | +} |
| 214 | +``` |
| 215 | + |
| 216 | +#### 🦀 Rust |
| 217 | + |
| 218 | +```rust |
| 219 | +use std::rc::Rc; |
| 220 | +use std::cell::RefCell; |
| 221 | + |
| 222 | +impl Solution { |
| 223 | + pub fn delete_node(root: Option<Rc<RefCell<TreeNode>>>, key: i32) -> Option<Rc<RefCell<TreeNode>>> { |
| 224 | + fn get_min(node: Rc<RefCell<TreeNode>>) -> Rc<RefCell<TreeNode>> { |
| 225 | + let mut cur = node; |
| 226 | + while cur.borrow().left.is_some() { |
| 227 | + cur = cur.borrow().left.clone().unwrap(); |
| 228 | + } |
| 229 | + cur |
| 230 | + } |
| 231 | + |
| 232 | + match root { |
| 233 | + None => None, |
| 234 | + Some(node) => { |
| 235 | + let val = node.borrow().val; |
| 236 | + if key < val { |
| 237 | + let left = Self::delete_node(node.borrow().left.clone(), key); |
| 238 | + node.borrow_mut().left = left; |
| 239 | + Some(node) |
| 240 | + } else if key > val { |
| 241 | + let right = Self::delete_node(node.borrow().right.clone(), key); |
| 242 | + node.borrow_mut().right = right; |
| 243 | + Some(node) |
| 244 | + } else { |
| 245 | + let left = node.borrow_mut().left.take(); |
| 246 | + let right = node.borrow_mut().right.take(); |
| 247 | + if left.is_none() { |
| 248 | + return right; |
| 249 | + } |
| 250 | + if right.is_none() { |
| 251 | + return left; |
| 252 | + } |
| 253 | + let min_node = get_min(right.clone().unwrap()); |
| 254 | + node.borrow_mut().val = min_node.borrow().val; |
| 255 | + node.borrow_mut().right = Self::delete_node(right, node.borrow().val); |
| 256 | + Some(node) |
| 257 | + } |
| 258 | + } |
| 259 | + } |
| 260 | + } |
| 261 | +} |
| 262 | +``` |
| 263 | + |
| 264 | +<!-- tabs:end --> |
| 265 | + |
| 266 | +<!-- solution:end --> |
0 commit comments