所以我基本上有函数avl?运行在 O(n^2) 中,这是因为每次我递归时,我都在调用高度,它是 O(n) 函数(其中 n 是树中的节点数)。
(define (height t)
(cond
[(empty? t) 0]
[else (+ 1 (max (height (BST-left t)) (height (BST-right t))))]))
(define (avl? t)
(cond
[(empty? t) #t]
[else (and (avl? (BST-left t))
(avl? (BST-right t))
(>= 1 (abs (- (height (BST-left t))
(height (BST-right t))))))]))
我的问题是我想做avl?在 O(n) 时间内运行。我得到了提示:“无论你应用多大的 BST,你都应该尽量限制在恒定时间内调用你的高度函数。这样,你可以获得 O(n) 的运行时间。” ......我不知道如何让我的身高在恒定时间内运行。有什么建议让我做avl吗?在 O(n) 而不是 O(n^2) 中运行?