如何知道二叉树是否是有序方案

时间:2014-06-01 10:21:02

标签: scheme binary-search-tree sorted

如果二进制树的所有子节点都在左侧分支下,则会对其进行排序 适当年龄的根和分支的数据,反过来,二元树 左右分支也被排序。写下程序 (ordered-btree?btree)接收二叉树作为参数并返回 如果有序则为真,否则为假。

我该怎么做?

2 个答案:

答案 0 :(得分:0)

如果其中一个子节点的顺序错误,您将为空节点或叶节点true创建一个返回false的递归过程。默认情况下(如果没有前一个匹配)结果是ordered-btree?形式的两个子项的and递归。例如。 (and (ordered-btree? left-child) (ordered-btree? right-child))

请注意,truefalse不是标准Scheme。 #t#f是。{

修改,因为Óscar发布的代码我也会发布我的缓冲区:

(define (tree-sorted? tree)
  (let ts-minmax ((tree tree) (minv -Inf.0) (maxv +Inf.0))    
    (or (tree-empty? tree)
        (let ((value (tree-value tree)))
          (and (<= minv value maxv)
               (ts-minmax (tree-left  tree) minv  value)
               (ts-minmax (tree-right tree) value maxv))))))

;; these are just to document how the tree is built up
(define (make-tree value left right) (list value left right))
(define tree-value car)
(define tree-left cadr)
(define tree-right caddr)
(define tree-empty? null?)
(define tree-empty '())

它的工作原理是,无论何时处理左子,您都知道您不应该拥有比当前节点更高的值。对于正确的孩子,您不应该遇到比当前节点更低的值。当您遍历时,maxvminv会缩小到唯一有效的范围。作为起点,我使用负和正不定式,使根节点具有任何值。

答案 1 :(得分:0)

有几种方法可以解决这个问题。我假设树中没有重复的元素,并且你已经编写了帮助程序,用于测试树是否为空,是否是叶子(即左右子树都是空的),用于返回左右子树,每个节点中的值,树中的最小值和最大值 - 这些应该是无关紧要的。第一个实现紧跟问题中提到的递归定义,但效率不高:

(define (ordered-btree? btree)
        ; if the tree is empty or is a leaf
  (cond ((or (is-empty? btree) (is-leaf? btree))
         ; then it's sorted
         true)
        ; else if the right subtree is empty
        ((is-empty? (right-tree btree))
         ; then test whether the current node's value is greater than
         ; the left subtree's maximum, and advance recursion over left
         (and (> (node-value btree) (max-value (left-tree btree)))
              (ordered-btree? (left-tree btree))))
        ; else if the left subtree is empty
        ((is-empty? (left-tree btree))
         ; then test whether the current node's value is less than
         ; the right subtree's minimum, and advance recursion over right
         (and (< (node-value btree) (min-value (right-tree btree)))
              (ordered-btree? (right-tree btree))))
        ; otherwise if both subtrees are non-empty
        (else                           
         ; then perform the same tests as above for both subtrees
         (and (> (node-value btree) (max-value (left-tree btree)))
              (< (node-value btree) (min-value (right-tree btree)))
              (ordered-btree? (left-tree btree))
              (ordered-btree? (right-tree btree))))))

第二种方法是使用in-order traversal获取树值的列表,然后检查返回的列表是否已排序。这是一个更有效的解决方案,我将概述它 - 再次假设正确的帮助程序已经到位:

(define (ordered-btree? btree)
  (is-sorted?         ; check whether a list of values is sorted
   (inorder-traversal ; return the in-order traversal of a tree as a list
    btree)))          ; a binary search tree