mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-06 23:28:29 +08:00
0450.删除二叉搜索树中的节点 加入Ruby递归实现
This commit is contained in:
@ -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">
|
||||
|
Reference in New Issue
Block a user