0450.删除二叉搜索树中的节点 加入Ruby递归实现

This commit is contained in:
Lane Zhang
2024-11-04 12:07:27 +08:00
parent 42d84f8a7f
commit 4c397b64f5

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"> <p align="center">
<a href="https://programmercarl.com/other/kstar.html" target="_blank"> <a href="https://programmercarl.com/other/kstar.html" target="_blank">