我正在尝试用球拍打造一棵树。 目前我已经构建了一个“静态”树,仅用于测试插入方法。它在树上运行到正确的位置,但无法插入新节点。
这是树:
(define bst
(make-node 4
(make-node 2 empty
(make-node 3 empty empty))
(make-node 5 empty
(make-node 11 empty
(make-node 12 empty
(make-node 13 empty empty))))))
插入方法(我留下了所有调试打印,因此很容易看到发生了什么,树是正确的):
(define (insert ABB val)
(cond[(empty? ABB)(make-node val empty empty)]
[(< val (node-val ABB))
(cond
[(empty? (node-left ABB))
(printf "\nEntered here\n")
(node-left ABB)(make-node val empty empty) ; this doesn't work
(printf "\nABB node-left: ~a" (node-left ABB))
(printf "\nABB node-left: ~a" (node-val ABB))]
[else
(printf "\nABB node-left (else): ~a" (node-left ABB))
(insert ((node-left ABB) val))]
)
]
[(> val (node-val ABB))
(cond
[(empty? (node-right ABB))
(node-left ABB)(make-node val empty empty) ; this doesn't work
(printf "\nABB node-val (empty): ~a" (node-val ABB))
(printf "\nEntered here 2\n")
(node-right ABB)(make-node val empty empty)
(printf "\nABB node-r:")])]
[else
(printf "\nABB node-val (else): ~a" (node-val ABB))
(printf "\nABB node-right (else): ~a" (node-right ABB))
(insert (node-right ABB) val)])
]
)
)
之后我试图插入17:
(insert bst 17)
以列表形式打印树:
(define (tree->list tree)
(if (empty? tree)
empty
(append (tree->list (node-right tree))
(cons (node-val tree)
(tree->list (node-left tree))))))
(printf "\n\nPrinting tree as list: \n")
(tree->list bst)
输出:
Printing tree as list:
'(13 12 11 5 4 3 2)
'17'没有显示出来。我无法将新节点分配给当前节点的左/右字段(ABB指向它)。这有什么问题?