二叉表达式树

Binary Expression Tree

我是 haskell 的新手,我有一个问题。我想为前任拿单。 [0,1,0,0,1,1,0,1] 并将元素放入树结构中;

data Tree = Leaf Int | Node String (Tree) (Tree)

到目前为止写了下面的代码但是它给出了一个错误。

bdd (x:xs)= if elem x [0..9] then Leaf x else Node x (Tree) (Tree)

感谢您的帮助!

您的代码尝试将 x 放入 Leaf,要求它是 Int,并且还尝试将其放入 Node,要求它成为 String。当然 IntString 是不同的类型,所以这不会编译。此外,Tree 是一个类型构造函数,因此您不能在术语中使用它。您的代码实际上应该做什么?

您没有在函数的递归调用中使用 Tree 构造函数,bdd 应该 return a Tree,这是使用 LeafNode,但请注意,Node 应该用 2 棵树构建,也应该用 LeafNode 构建,而不是 Tree

bdd :: [Int] -> Tree
bdd (x:xs)= if elem x [0..9] then Leaf x else Node (show x) (bdd xs) (bdd xs)

你应该检查你想如何正确构建树,这只是一个例子。