zoukankan      html  css  js  c++  java
  • 【Scheme】树结构

    将表作为序列的表示方式,可以推广到元素本身也是序列的序列。例如,我们可以认为对象((1 2) 3 4)是通过(cons (list 1 2) (list 3 4))构造出来的。
    这个表包含三个项,其中第一项本身又是一个表(1 2)。因此可以将其看做一个树形结构:根为((1 2) 3 4),有3个子树分别为(1 2)、3、4。 因3、4不再具有子树,故称它们为叶子节点。
    同理(1 2)节点有1、2两个叶子节点。如下图所示:

    以下是树的操作


    计算叶子数:

    (define (count-leaves tree)
      (cond ((null? tree) 0)
            ((not (pair? tree)) 1)
            (else (+ (count-leaves (car tree))
                     (count-leaves (cdr tree))))))
    

    深度反转:

    (define (deep-reverse2 items)
      (cond ((null? items) null)
            ((not (pair? items)) items)
            (else (append (deep-reverse2 (cdr items)) (list (deep-reverse2 (car items))))))
    

    叶子从左向右输出

    (define (fringe items)
      (cond ((null? items) null)
            ((not (pair? items)) (list items))   
            (else (append (fringe (car items)) (fringe (cdr items))))))
    

    对树的映射

    方法1:

    (define (tree-map proc tree)
      (cond ((null? tree) null)
            ((not (pair? tree)) (proc tree));叶子直接返回
            (else (cons (tree-map proc (car tree));左子树
                        (tree-map proc (cdr tree))))));右子树
    
    

    方法2:

    
    (define (tree-map2 proc tree)
      (map (lambda (sub-tree);对tree中的每一个子树
             (if (pair? sub-tree);如果是序对
                 (tree-map2 proc sub-tree);递归对该子树执行map
                 (proc sub-tree))) tree));返回叶子
    
  • 相关阅读:
    oracle性能调优
    oracle常用函数
    plsql的安装与使用
    WSAIoctl
    SQL中大概有这么几种JOIN
    如何取分组最大值记录
    having
    MSSQL—按照某一列分组后取前N条记录
    sql之left join、right join、inner join的区别
    delphi 接收心跳包怎么写
  • 原文地址:https://www.cnblogs.com/cknightx/p/6802610.html
Copyright © 2011-2022 走看看