|
|
@ -10,9 +10,10 @@ import utils
|
|
|
|
class BinarySearchTree {
|
|
|
|
class BinarySearchTree {
|
|
|
|
private var root: TreeNode?
|
|
|
|
private var root: TreeNode?
|
|
|
|
|
|
|
|
|
|
|
|
init(nums: [Int]) {
|
|
|
|
/* 构造方法 */
|
|
|
|
let nums = nums.sorted() // 排序数组
|
|
|
|
init() {
|
|
|
|
root = buildTree(nums: nums, i: 0, j: nums.count - 1) // 构建二叉搜索树
|
|
|
|
// 初始化空树
|
|
|
|
|
|
|
|
root = nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/* 获取二叉树根节点 */
|
|
|
|
/* 获取二叉树根节点 */
|
|
|
@ -20,20 +21,6 @@ class BinarySearchTree {
|
|
|
|
root
|
|
|
|
root
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/* 构建二叉搜索树 */
|
|
|
|
|
|
|
|
func buildTree(nums: [Int], i: Int, j: Int) -> TreeNode? {
|
|
|
|
|
|
|
|
if i > j {
|
|
|
|
|
|
|
|
return nil
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
// 将数组中间节点作为根节点
|
|
|
|
|
|
|
|
let mid = (i + j) / 2
|
|
|
|
|
|
|
|
let root = TreeNode(x: nums[mid])
|
|
|
|
|
|
|
|
// 递归建立左子树和右子树
|
|
|
|
|
|
|
|
root.left = buildTree(nums: nums, i: i, j: mid - 1)
|
|
|
|
|
|
|
|
root.right = buildTree(nums: nums, i: mid + 1, j: j)
|
|
|
|
|
|
|
|
return root
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
/* 查找节点 */
|
|
|
|
/* 查找节点 */
|
|
|
|
func search(num: Int) -> TreeNode? {
|
|
|
|
func search(num: Int) -> TreeNode? {
|
|
|
|
var cur = root
|
|
|
|
var cur = root
|
|
|
@ -154,8 +141,12 @@ enum _BinarySearchTree {
|
|
|
|
/* Driver Code */
|
|
|
|
/* Driver Code */
|
|
|
|
static func main() {
|
|
|
|
static func main() {
|
|
|
|
/* 初始化二叉搜索树 */
|
|
|
|
/* 初始化二叉搜索树 */
|
|
|
|
let nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
|
|
|
|
let bst = BinarySearchTree()
|
|
|
|
let bst = BinarySearchTree(nums: nums)
|
|
|
|
// 请注意,不同的插入顺序会生成不同的二叉树,该序列可以生成一个完美二叉树
|
|
|
|
|
|
|
|
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")
|
|
|
|
print("\n初始化的二叉树为\n")
|
|
|
|
PrintUtil.printTree(root: bst.getRoot())
|
|
|
|
PrintUtil.printTree(root: bst.getRoot())
|
|
|
|
|
|
|
|
|
|
|
|