Haskell中的树遍历

时间:2012-02-22 18:46:12

标签: haskell

以下是遍历无法正常工作的树的代码:

data Tree = Leaf Int | Node Int Tree Tree deriving Show 

preorder(Leaf n) = [n]
preorder(Node n t0 t1) = [n] ++ (preorder t0) ++ (preorder t1)

inorder(Leaf n) = [n]
inorder(Node n t0 t1) = (inorder t0) ++ [n] ++ (inorder t1)

postorder(Leaf n) = [n]
postorder(Node n t0 t1) = (postorder t0) ++ (postorder t1) ++ [n]

我被要求执行以下操作:

Node 8 (Node 3 (Leaf 5) (Leaf 2)) (Node 1 (Leaf 9) (Leaf 6))

当我执行上面的语句时,它返回原样,它应该返回:

preorder t = [8,3,5,2,1,9,6]

inorder t = [5,3,2,8,9,1,6]

postorder t =[5,2,3,9,6,1,8]

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:5)

你所做的:

Node 8 (Node 3 (Leaf 5) (Leaf 2)) (Node 1 (Leaf 9) (Leaf 6))

Tree类型的。您可以通过为其创建绑定定义来为此值指定名称。如果您正在使用源文件,则可以执行

myTree = Node 8 (Node 3 (Leaf 5) (Leaf 2)) (Node 1 (Leaf 9) (Leaf 6))

或者给它一个类型签名

myTree :: Tree  -- this is the type signature
myTree = Node 8 (Node 3 (Leaf 5) (Leaf 2)) (Node 1 (Leaf 9) (Leaf 6))

如果您正在使用解释器 ghci ,则可以使用 let 创建新定义:

Prelude> let myTree = Node 8 (Node 3 (Leaf 5) (Leaf 2)) (Node 1 (Leaf 9) (Leaf 6))

您的任务似乎是在给出此树时评估每个函数postorderinorderpreorder。如果您在源文件中,则需要将结果保存在定义中:

inOrderResult :: [Int]
inOrderResult = inorder myTree

(请注意,我们将myTree作为参数传递给函数 inorder。)如果您正在使用{{ 1}},只需输入

ghci

会将结果打印到终端。