【问题标题】:build a tree with given number of nodes用给定数量的节点构建一棵树
【发布时间】:2017-10-08 00:42:45
【问题描述】:

我有一个树的数据结构,其中的节点有一个或两个子节点。我可以生成具有给定最大深度的随机树。现在我想用给定的最大节点数(/叶子)生成这些随机三个。这是我的结构:

import System.Random

data Tree a = Leaf 
            | NodeTwo (Tree a) (Tree a)
            | NodeOne (Tree a)
            deriving (Show)

create :: RandomGen g => Int -> Int -> Int -> Int -> g -> Tree a
create depth maxNodeOne maxNodeTwo maxLeaf g
    | (depth == 0) = Leaf
    | (x >= a && x < c && (maxNodeTwo /= 0)) 
      = let (g1, g2) = split g in 
      NodeTwo (create (depth -1) maxNodeOne (maxNodeTwo-1) 
      maxLeaf g1) (create (depth -1) maxNodeOne 
      (maxNodeTwo-1) maxLeaf g2) 
    |(x >= c && x < 2*c && (maxNodeOne /= 0))
     = NodeOne (create  (depth -1) 
    (maxNodeOne -1) maxNodeTwo maxLeaf g')
    | otherwise = Leaf
    where (x, g') = next g
          (a, b) = genRange g
          c = (b - a) `div` 3

countFnk :: Tree a -> Int             
countFnk (Leaf) = 0
countFnk (NodeOne a) = countFnk a
countFnk (NodeTwo a b) = 1 + countFnk a + countFnk b

countLam :: Tree a -> Int             
countLam (Leaf) = 0
countLam (NodeOne a) = 1 + countLam a
countLam (NodeTwo a b) = countLam a + countLam b

countLeaf :: Tree a -> Int             
countLeaf (Leaf) = 1
countLeaf (NodeOne a) = countLeaf a
countLeaf (NodeTwo a b) = countLeaf a + countLeaf b

这个尝试当然失败了。我不知道如何减少递归中节点的计数器。我也有一些函数可以让我获得节点(/叶子)的数量,但我不知道如何在我的创建函数中使用这些函数,因为它们需要一个完成的树来扫描。 感谢您的帮助。

【问题讨论】:

    标签: haskell tree binary-tree nodes


    【解决方案1】:

    最明显的问题在于您的NodeTwo 案例。到达那个时候,您的“预算”为NodeTwos 和NodeOnes。但是你告诉你的新树的两个分支同样的事情:“随意花费整个预算”!当然,如果他们都这样做,您最终会花费两倍的预算。

    您需要一些方法来协商树的每个分支的预算。有很多方法可以做到这一点;例如,让一个分支访问整个预算,而将剩下的任何东西都交给第二个分支。或者,您可以在创建任一分支之前决定如何在它们之间分配预算,并只给每个分支您总预算的一部分。

    这两种方法中的任何一种都可能会在您的随机性中引入一些偏见,这对您来说可能很重要,也可能无关紧要。您应该想出一种方法来处理预算会计,以产生您想要的随机树的种类。

    一旦你解决了这个问题,你就会遇到其他问题:有些约束集是不可能建立一个适合它们的树的!最值得注意的是,如果maxLeaf 为零,则根本无法创建任何类型的树,因为每棵树在某处至少有一个叶节点。您必须小心,不要构建任何可用叶子太少的子树,以免它们终止。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多