Skip to content

Commit 37c7540

Browse files
iamAntimPalAntim-IWPIamShiwangi
committed
Update readme.md
Co-Authored-By: Antim-IWP <[email protected]> Co-Authored-By: Shiwangi Srivastava <[email protected]>
1 parent 75f5468 commit 37c7540

File tree

1 file changed

+363
-0
lines changed

1 file changed

+363
-0
lines changed
Lines changed: 363 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,363 @@
1+
2+
<!-- problem:start -->
3+
4+
# [450. Delete Node in a BST](https://leetcode.com/problems/delete-node-in-a-bst)
5+
6+
7+
- **comments**: true
8+
- **difficulty**: Medium
9+
- **tags**:
10+
- Tree
11+
- Binary Search Tree
12+
- Binary Tree
13+
---
14+
## Description
15+
16+
<!-- description:start -->
17+
18+
<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>
19+
20+
<p>Basically, the deletion can be divided into two stages:</p>
21+
22+
<ol>
23+
<li>Search for a node to remove.</li>
24+
<li>If the node is found, delete the node.</li>
25+
</ol>
26+
27+
<p>&nbsp;</p>
28+
<p><strong class="example">Example 1:</strong></p>
29+
<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;" />
30+
<pre>
31+
<strong>Input:</strong> root = [5,3,6,2,4,null,7], key = 3
32+
<strong>Output:</strong> [5,4,6,2,null,null,7]
33+
<strong>Explanation:</strong> Given key to delete is 3. So we find the node with value 3 and delete it.
34+
One valid answer is [5,4,6,2,null,null,7], shown in the above BST.
35+
Please notice that another valid answer is [5,2,6,null,4,null,7] and it&#39;s also accepted.
36+
<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;" />
37+
</pre>
38+
39+
<p><strong class="example">Example 2:</strong></p>
40+
41+
<pre>
42+
<strong>Input:</strong> root = [5,3,6,2,4,null,7], key = 0
43+
<strong>Output:</strong> [5,3,6,2,4,null,7]
44+
<strong>Explanation:</strong> The tree does not contain a node with value = 0.
45+
</pre>
46+
47+
<p><strong class="example">Example 3:</strong></p>
48+
49+
<pre>
50+
<strong>Input:</strong> root = [], key = 0
51+
<strong>Output:</strong> []
52+
</pre>
53+
54+
<p>&nbsp;</p>
55+
<p><strong>Constraints:</strong></p>
56+
57+
<ul>
58+
<li>The number of nodes in the tree is in the range <code>[0, 10<sup>4</sup>]</code>.</li>
59+
<li><code>-10<sup>5</sup> &lt;= Node.val &lt;= 10<sup>5</sup></code></li>
60+
<li>Each node has a <strong>unique</strong> value.</li>
61+
<li><code>root</code> is a valid binary search tree.</li>
62+
<li><code>-10<sup>5</sup> &lt;= key &lt;= 10<sup>5</sup></code></li>
63+
</ul>
64+
65+
<p>&nbsp;</p>
66+
<p><strong>Follow up:</strong> Could you solve it with time complexity <code>O(height of tree)</code>?</p>
67+
68+
<!-- description:end -->
69+
70+
## Solutions
71+
72+
<!-- solution:start -->
73+
74+
### Solution 1
75+
76+
<!-- tabs:start -->
77+
78+
#### Python3
79+
80+
```python
81+
# Definition for a binary tree node.
82+
# class TreeNode:
83+
# def __init__(self, val=0, left=None, right=None):
84+
# self.val = val
85+
# self.left = left
86+
# self.right = right
87+
class Solution:
88+
def deleteNode(self, root: Optional[TreeNode], key: int) -> Optional[TreeNode]:
89+
if root is None:
90+
return None
91+
if root.val > key:
92+
root.left = self.deleteNode(root.left, key)
93+
return root
94+
if root.val < key:
95+
root.right = self.deleteNode(root.right, key)
96+
return root
97+
if root.left is None:
98+
return root.right
99+
if root.right is None:
100+
return root.left
101+
node = root.right
102+
while node.left:
103+
node = node.left
104+
node.left = root.left
105+
root = root.right
106+
return root
107+
```
108+
109+
#### Java
110+
111+
```java
112+
/**
113+
* Definition for a binary tree node.
114+
* public class TreeNode {
115+
* int val;
116+
* TreeNode left;
117+
* TreeNode right;
118+
* TreeNode() {}
119+
* TreeNode(int val) { this.val = val; }
120+
* TreeNode(int val, TreeNode left, TreeNode right) {
121+
* this.val = val;
122+
* this.left = left;
123+
* this.right = right;
124+
* }
125+
* }
126+
*/
127+
class Solution {
128+
public TreeNode deleteNode(TreeNode root, int key) {
129+
if (root == null) {
130+
return null;
131+
}
132+
if (root.val > key) {
133+
root.left = deleteNode(root.left, key);
134+
return root;
135+
}
136+
if (root.val < key) {
137+
root.right = deleteNode(root.right, key);
138+
return root;
139+
}
140+
if (root.left == null) {
141+
return root.right;
142+
}
143+
if (root.right == null) {
144+
return root.left;
145+
}
146+
TreeNode node = root.right;
147+
while (node.left != null) {
148+
node = node.left;
149+
}
150+
node.left = root.left;
151+
root = root.right;
152+
return root;
153+
}
154+
}
155+
```
156+
157+
#### C++
158+
159+
```cpp
160+
/**
161+
* Definition for a binary tree node.
162+
* struct TreeNode {
163+
* int val;
164+
* TreeNode *left;
165+
* TreeNode *right;
166+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
167+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
168+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
169+
* };
170+
*/
171+
class Solution {
172+
public:
173+
TreeNode* deleteNode(TreeNode* root, int key) {
174+
if (!root) return root;
175+
if (root->val > key) {
176+
root->left = deleteNode(root->left, key);
177+
return root;
178+
}
179+
if (root->val < key) {
180+
root->right = deleteNode(root->right, key);
181+
return root;
182+
}
183+
if (!root->left) return root->right;
184+
if (!root->right) return root->left;
185+
TreeNode* node = root->right;
186+
while (node->left) node = node->left;
187+
node->left = root->left;
188+
root = root->right;
189+
return root;
190+
}
191+
};
192+
```
193+
194+
#### Go
195+
196+
```go
197+
/**
198+
* Definition for a binary tree node.
199+
* type TreeNode struct {
200+
* Val int
201+
* Left *TreeNode
202+
* Right *TreeNode
203+
* }
204+
*/
205+
func deleteNode(root *TreeNode, key int) *TreeNode {
206+
if root == nil {
207+
return nil
208+
}
209+
if root.Val > key {
210+
root.Left = deleteNode(root.Left, key)
211+
return root
212+
}
213+
if root.Val < key {
214+
root.Right = deleteNode(root.Right, key)
215+
return root
216+
}
217+
if root.Left == nil {
218+
return root.Right
219+
}
220+
if root.Right == nil {
221+
return root.Left
222+
}
223+
node := root.Right
224+
for node.Left != nil {
225+
node = node.Left
226+
}
227+
node.Left = root.Left
228+
root = root.Right
229+
return root
230+
}
231+
```
232+
233+
#### TypeScript
234+
235+
```ts
236+
/**
237+
* Definition for a binary tree node.
238+
* class TreeNode {
239+
* val: number
240+
* left: TreeNode | null
241+
* right: TreeNode | null
242+
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
243+
* this.val = (val===undefined ? 0 : val)
244+
* this.left = (left===undefined ? null : left)
245+
* this.right = (right===undefined ? null : right)
246+
* }
247+
* }
248+
*/
249+
250+
function deleteNode(root: TreeNode | null, key: number): TreeNode | null {
251+
if (root == null) {
252+
return root;
253+
}
254+
const { val, left, right } = root;
255+
if (val > key) {
256+
root.left = deleteNode(left, key);
257+
} else if (val < key) {
258+
root.right = deleteNode(right, key);
259+
} else {
260+
if (left == null && right == null) {
261+
root = null;
262+
} else if (left == null || right == null) {
263+
root = left || right;
264+
} else {
265+
if (right.left == null) {
266+
right.left = left;
267+
root = right;
268+
} else {
269+
let minPreNode = right;
270+
while (minPreNode.left.left != null) {
271+
minPreNode = minPreNode.left;
272+
}
273+
const minVal = minPreNode.left.val;
274+
root.val = minVal;
275+
minPreNode.left = deleteNode(minPreNode.left, minVal);
276+
}
277+
}
278+
}
279+
return root;
280+
}
281+
```
282+
283+
#### Rust
284+
285+
```rust
286+
// Definition for a binary tree node.
287+
// #[derive(Debug, PartialEq, Eq)]
288+
// pub struct TreeNode {
289+
// pub val: i32,
290+
// pub left: Option<Rc<RefCell<TreeNode>>>,
291+
// pub right: Option<Rc<RefCell<TreeNode>>>,
292+
// }
293+
//
294+
// impl TreeNode {
295+
// #[inline]
296+
// pub fn new(val: i32) -> Self {
297+
// TreeNode {
298+
// val,
299+
// left: None,
300+
// right: None
301+
// }
302+
// }
303+
// }
304+
use std::cell::RefCell;
305+
use std::rc::Rc;
306+
impl Solution {
307+
fn dfs(root: &Option<Rc<RefCell<TreeNode>>>) -> i32 {
308+
let node = root.as_ref().unwrap().borrow();
309+
if node.left.is_none() {
310+
return node.val;
311+
}
312+
Self::dfs(&node.left)
313+
}
314+
315+
pub fn delete_node(
316+
mut root: Option<Rc<RefCell<TreeNode>>>,
317+
key: i32,
318+
) -> Option<Rc<RefCell<TreeNode>>> {
319+
if root.is_some() {
320+
let mut node = root.as_mut().unwrap().borrow_mut();
321+
match node.val.cmp(&key) {
322+
std::cmp::Ordering::Less => {
323+
node.right = Self::delete_node(node.right.take(), key);
324+
}
325+
std::cmp::Ordering::Greater => {
326+
node.left = Self::delete_node(node.left.take(), key);
327+
}
328+
std::cmp::Ordering::Equal => {
329+
match (node.left.is_some(), node.right.is_some()) {
330+
(false, false) => {
331+
return None;
332+
}
333+
(true, false) => {
334+
return node.left.take();
335+
}
336+
(false, true) => {
337+
return node.right.take();
338+
}
339+
(true, true) => {
340+
if node.right.as_ref().unwrap().borrow().left.is_none() {
341+
let mut r = node.right.take();
342+
r.as_mut().unwrap().borrow_mut().left = node.left.take();
343+
return r;
344+
} else {
345+
let val = Self::dfs(&node.right);
346+
node.val = val;
347+
node.right = Self::delete_node(node.right.take(), val);
348+
}
349+
}
350+
};
351+
}
352+
}
353+
}
354+
root
355+
}
356+
}
357+
```
358+
359+
<!-- tabs:end -->
360+
361+
<!-- solution:end -->
362+
363+
<!-- problem:end -->

0 commit comments

Comments
 (0)