问题
I've got work to do, but i dunno how to do it. I have Bin tree
1
/ \
2 3
/ \ / \
4 5 6 7
And I need to find the way from root to Node with the coord [i, j]. For example: (2, 2) -> [1, 3, 6]
fromRoot :: Int -> Int -> Tree a -> [a]
I wrote some function for Index and BinTree, but how to make main function i dont know.
data Tree a = Node (Tree a) a (Tree a)
index :: Tree a -> Int -> Int -> a
index (Node _ x _ ) 0 _ = x
index (Node l x r) i j | ((border i)<j) = index r (i-1) (j-(border i)-1)
| otherwise = index l (i-1) j
border :: Int -> Int
border 0 = 0
border 1 = 0
border l = 2*(border (l-1))+1
myBuild :: Int -> Tree Int
myBuild n = (Node (myBuild (n*2)) n (myBuild (n*2+1)))
回答1:
Since this is homework I won't give a complete solution, but some hints:
- how do you represent an empty tree with your Tree type?
- how do you represent the example tree (or any other finite tree)?
Considering the main function: you don't necessarily need one, a good way to start is running
ghci your_source_file.hs
You can then evaluate parts of your program, e.g.:
fromRoot 2 3 t1 -- if you have a t1 is a tree
Apart from that you could write a main function like this:
test_tree = ... -- you need to fill in the dots (see questions above)
main :: IO ()
main = do print (fromRoot 2 2 test_tree)
If you need to find some documentation, use http://haskell.org/hoogle/
来源:https://stackoverflow.com/questions/8077802/haskell-get-path-from-every-leaf-node-to-root-in-a-bin-tree-structure