Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 4c397b6

Browse files
committed
0450.删除二叉搜索树中的节点 加入Ruby递归实现
1 parent 42d84f8 commit 4c397b6

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

‎problems/0450.删除二叉搜索树中的节点.md

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -801,6 +801,40 @@ impl Solution {
801801
}
802802
```
803803

804+
### Ruby
805+
> 递归法:
806+
```ruby
807+
# @param {TreeNode} root
808+
# @param {Integer} key
809+
# @return {TreeNode}
810+
def delete_node(root, key)
811+
return nil if root.nil?
812+
813+
right = root.right
814+
left = root.left
815+
816+
if root.val == key
817+
return right if left.nil?
818+
return left if right.nil?
819+
820+
node = right
821+
while node.left
822+
node = node.left
823+
end
824+
node.left = left
825+
826+
return right
827+
end
828+
829+
if root.val > key
830+
root.left = delete_node(left, key)
831+
else
832+
root.right = delete_node(right, key)
833+
end
834+
835+
return root
836+
end
837+
```
804838

805839
<p align="center">
806840
<a href="https://programmercarl.com/other/kstar.html" target="_blank">

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /