refactor: remove buildTree (#716)

pull/718/head^2
nuomi1 1 year ago committed by GitHub
parent fd84d4443e
commit 22d1135e04
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -10,9 +10,10 @@ import utils
class BinarySearchTree {
private var root: TreeNode?
init(nums: [Int]) {
let nums = nums.sorted() //
root = buildTree(nums: nums, i: 0, j: nums.count - 1) //
/* */
init() {
//
root = nil
}
/* */
@ -20,20 +21,6 @@ class BinarySearchTree {
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? {
var cur = root
@ -154,8 +141,12 @@ enum _BinarySearchTree {
/* Driver Code */
static func main() {
/* */
let nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
let bst = BinarySearchTree(nums: nums)
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())

Loading…
Cancel
Save