简体   繁体   English

Haskell 范围内的二叉树的子树

[英]Subtrees of Binary Trees in a range Haskell

I have a Binary Tree defined as the following:我有一个定义如下的二叉树:

data BSTree = Void | BSNode BSTree Integer BSTree

and would like to write a function并想写一个 function

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

which returns all subset of trees with a <= key < b.它返回具有 <= key < b 的所有树的子集。

I tried the following我尝试了以下

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)

but do not get the correct output.但没有得到正确的 output。 Could someone point out the flaw in my logic?有人能指出我的逻辑缺陷吗?

I each step of the recursion, you should provide a and b arguments:我递归的每一步,都应该提供ab arguments:

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)

With this example:用这个例子:

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

I tried the following code:我尝试了以下代码:

subTree x y (BSNode leftSubTree leaf rightSubTree) 
    | leaf < x = BSNode Void leaf (subTree leaf y rightSubTree)
    | leaf > y = BSNode (subTree x leaf leftSubTree) leaf Void
    | x <= leaf && leaf < y = BSNode (subTree x y leftSubTree) leaf (subTree x y rightSubTree)

However, it does not return a tree with elements within my defined interval.但是,它不会返回包含我定义的时间间隔内的元素的树。 What is wrong?怎么了?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM