Merge pull request #2821 from gazeldx/P0450

0450.删除二叉搜索树中的节点 加入Ruby递归实现
This commit is contained in:
程序员Carl
2024-12-16 21:07:15 +08:00
committed by GitHub

View File

@ -801,6 +801,40 @@ impl Solution {
}
```
### Ruby
> 递归法:
```ruby
# @param {TreeNode} root
# @param {Integer} key
# @return {TreeNode}
def delete_node(root, key)
return nil if root.nil?
right = root.right
left = root.left
if root.val == key
return right if left.nil?
return left if right.nil?
node = right
while node.left
node = node.left
end
node.left = left
return right
end
if root.val > key
root.left = delete_node(left, key)
else
root.right = delete_node(right, key)
end
return root
end
```
<p align="center">
<a href="https://programmercarl.com/other/kstar.html" target="_blank">