【问题标题】:Subtrees of Binary Trees in a range HaskellHaskell 范围内的二叉树的子树
【发布时间】:2020-02-07 03:06:56
【问题描述】:

我有一个定义如下的二叉树:

data BSTree = Void | BSNode BSTree Integer BSTree

想写一个函数

subTree:: Integer -> Integer -> BSTree -> BSTree

返回所有具有

我尝试了以下

subTree:: Integer -> Integer -> BSTree -> BSTree
subTree a b Void = Void
subTree a b (BSNode leftTree key rightTree) 
    | key < a = BSNode Void key (subTree key b rightTree)
    | b < key = BSNode (subTree a key leftTree) key Void
    | a <= key && b > key = BSNode (subTree a key leftTree) key (subTree key b rightTree)

但没有得到正确的输出。有人能指出我的逻辑缺陷吗?

【问题讨论】:

  • 提示:如果key &lt; a,您仍然返回一个包含 keyBSNodeb &lt; key 也是如此。
  • 与树的高度有什么关系?
  • 道歉,标题上的大脑褪色。 @WillemVanOnsem 这是真的,但我不确定我应该改用什么。
  • @AdityaSubramanian:你在右子树上递归,没有在那个级别构造一个节点。
  • 当然好!谢谢!

标签: haskell recursion tree


【解决方案1】:

我递归的每一步,都应该提供ab参数:

data BSTree = Void | BSNode BSTree Integer BSTree deriving Show

subTree:: Integer -> Integer -> BSTree -> BSTree
subTree a b Void = Void
subTree a b (BSNode leftTree key rightTree) 
 | key < a = --your logic here
 | b < key = -- your logic here
 | a <= key && b > key = BSNode (subTree a b leftTree) key (subTree a b rightTree)

t1 = BSNode Void 5 Void
t2 = BSNode Void 6 Void
t3 = BSNode Void 7 Void
t4 = BSNode t1 8 (BSNode t1 7 t2)

用这个例子:

   subTree 6 10 t4
=> BSNode Void 8 (BSNode Void 7 (BSNode Void 6 Void))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多