树节点的反向节点

时间:2014-06-04 06:48:43

标签: scheme racket

定义接收树作为参数并返回的反向树方法 投资了所有分支机构:

我这样做:

(define (reverse-tree t)
  (map (lambda (x)
         (if (list? x)
             (deep-reverse x)
             x))
       (reverse t)))


 (define tree '(40 (28 (9) (32)) (70 (52) (102))))


(reverse-tree tree)

我退回了这个:

(((102) (52) 70) ((32) (9) 28) 40)

但是我需要你返回反转的节点:

(40 (70 (102) (52)) (28 (32) (9)))

如何回到逆转的点头

2 个答案:

答案 0 :(得分:1)

对于BST想象一下,您有树的程序。 (make-tree value left right)tree-valuetree-lefttreee-right

(define (reverse-tree tree)
  (if (tree-null? tree)
      tree-null
      (make-tree (tree-value tree)
                 (reverse-tree (tree-right tree))
                 (reverse-tree (tree-left tree)))))

对于一个可以有两个以上孩子的树,我猜你会在每个孩子身上使用它并反转结果。

(define (reverse-tree tree)
  (if (tree-null? tree)
      tree-null
      (apply make-tree 
             (tree-value tree)
             (map reverse-tree (reverse (tree-children tree))))))

;; heres the documentation of the tree
(define (make-tree value . children)
  (cons value children))

(define tree-children cdr)
(define tree-value car)
(define tree-null? null?)
(define tree-null '())

答案 1 :(得分:0)

假设一个节点有0或2个分支,这里有一个简单的解决方案:

(define (reverse-tree tree)
  (if (null? tree)
      null
      (let ((root (car tree)) (tree (cdr tree)))
        (if (null? tree)
            (list root)
            (list root (reverse-tree (cadr tree)) (reverse-tree (car tree)))))))

测试

> (reverse-tree '(40 (28 (9) (32)) (70 (52) (102))))
'(40 (70 (102) (52)) (28 (32) (9)))