我在使用二叉搜索树时遇到问题并将其转换为列表。
(define-struct node (key val left right))
;; A binary search tree (bst) is either
;; empty, or
;; a structure (make-node k v l r), where
;; k is a number (the key),
;; v is a string (the value),
;; l is a bst, where every key in l is less than k, and
;; r is a bst, where every key in r is greater than k.
有人可以给我一些关于如何处理这个问题的提示吗?
创建一个使用二叉搜索树的函数bst,并返回二叉搜索树节点的值字段中所有字符串的列表,并且列表必须根据二叉搜索树中的键值按降序排列。
;;Examples: (bst (make-node 4 "James" (make-node 2 "Kien" empty empty)
;;(make-node 5 "Jack" empty (make-node 11 "Cole" empty empty)))) => (list "Cole" "Jack" "James" "Kien")
谢谢!
答案 0 :(得分:2)
基本上,您必须使用反向in-orden traversal(右子树/值/左子树)访问树中的所有节点,同时创建包含答案的列表。这些方面的东西:
(define (tree->list tree)
(if (empty? tree)
empty
(append (tree->list (node-right tree))
(cons (node-val tree)
(tree->list (node-left tree))))))
按预期工作:
(define bst
(make-node 4 "James"
(make-node 2 "Kien" empty empty)
(make-node 5 "Jack" empty
(make-node 11 "Cole" empty empty))))
(tree->list bst)
=> (list "Cole" "Jack" "James" "Kien")
答案 1 :(得分:0)
(define (tree->list tree)
(if(leaf? tree)
(list (node tree))
(cond((right-branch-only? tree)(append (list(node tree))
(tree->list (right-branch tree))))
((left-branch-only? tree)(append (list(node tree))
(tree->list (left-branch tree))))
(else(append (list (node tree))
(append (tree->list (left-branch tree))
(tree->list (right-branch tree))))))))