forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0450-delete-node-in-a-bst.swift
51 lines (48 loc) · 1.45 KB
/
0450-delete-node-in-a-bst.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/**
* Question Link: https://leetcode.com/problems/delete-node-in-a-bst/
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* public var val: Int
* public var left: TreeNode?
* public var right: TreeNode?
* public init() { self.val = 0; self.left = nil; self.right = nil; }
* public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; }
* public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) {
* self.val = val
* self.left = left
* self.right = right
* }
* }
*/
class Solution {
func deleteNode(_ root: TreeNode?, _ key: Int) -> TreeNode? {
if root == nil {
return root
}
if root!.val > key {
root?.left = deleteNode(root?.left, key)
} else if root!.val < key {
root?.right = deleteNode(root?.right, key)
} else {
if root?.left == nil {
return root?.right
} else if root?.right == nil {
return root?.left
} else {
let minNode = minNode(root: root?.right)
root?.val = minNode!.val
root?.right = deleteNode(root?.right, minNode!.val)
}
}
return root
}
func minNode(root: TreeNode?) -> TreeNode? {
var cur = root
while cur != nil && cur?.left != nil {
cur = cur?.left
}
return cur
}
}