You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
hello-algo/zh-hant/codes/swift/chapter_tree/binary_search_tree.swift

174 lines
4.7 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

/**
* File: binary_search_tree.swift
* Created Time: 2023-01-26
* Author: nuomi1 (nuomi1@qq.com)
*/
import utils
/* */
class BinarySearchTree {
private var root: TreeNode?
/* */
init() {
//
root = nil
}
/* */
func getRoot() -> TreeNode? {
root
}
/* */
func search(num: Int) -> TreeNode? {
var cur = root
//
while cur != nil {
// cur
if cur!.val < num {
cur = cur?.right
}
// cur
else if cur!.val > num {
cur = cur?.left
}
//
else {
break
}
}
//
return cur
}
/* */
func insert(num: Int) {
//
if root == nil {
root = TreeNode(x: num)
return
}
var cur = root
var pre: TreeNode?
//
while cur != nil {
//
if cur!.val == num {
return
}
pre = cur
// cur
if cur!.val < num {
cur = cur?.right
}
// cur
else {
cur = cur?.left
}
}
//
let node = TreeNode(x: num)
if pre!.val < num {
pre?.right = node
} else {
pre?.left = node
}
}
/* */
func remove(num: Int) {
//
if root == nil {
return
}
var cur = root
var pre: TreeNode?
//
while cur != nil {
//
if cur!.val == num {
break
}
pre = cur
// cur
if cur!.val < num {
cur = cur?.right
}
// cur
else {
cur = cur?.left
}
}
//
if cur == nil {
return
}
// = 0 or 1
if cur?.left == nil || cur?.right == nil {
// = 0 / 1 child = null /
let child = cur?.left ?? cur?.right
// cur
if cur !== root {
if pre?.left === cur {
pre?.left = child
} else {
pre?.right = child
}
} else {
//
root = child
}
}
// = 2
else {
// cur
var tmp = cur?.right
while tmp?.left != nil {
tmp = tmp?.left
}
// tmp
remove(num: tmp!.val)
// tmp cur
cur?.val = tmp!.val
}
}
}
@main
enum _BinarySearchTree {
/* Driver Code */
static func main() {
/* */
let bst = BinarySearchTree()
//
let nums = [8, 4, 12, 2, 6, 10, 14, 1, 3, 5, 7, 9, 11, 13, 15]
for num in nums {
bst.insert(num: num)
}
print("\n初始化的二元樹為\n")
PrintUtil.printTree(root: bst.getRoot())
/* */
let node = bst.search(num: 7)
print("\n查詢到的節點物件為 \(node!),節點值 = \(node!.val)")
/* */
bst.insert(num: 16)
print("\n插入節點 16 後,二元樹為\n")
PrintUtil.printTree(root: bst.getRoot())
/* */
bst.remove(num: 1)
print("\n刪除節點 1 後,二元樹為\n")
PrintUtil.printTree(root: bst.getRoot())
bst.remove(num: 2)
print("\n刪除節點 2 後,二元樹為\n")
PrintUtil.printTree(root: bst.getRoot())
bst.remove(num: 4)
print("\n刪除節點 4 後,二元樹為\n")
PrintUtil.printTree(root: bst.getRoot())
}
}