
Assume a tree is a subtree of the other if all elements of the first tree is included in the second with the exact structure; all parent-child relations are preserved with their order. data Tree = Empty | Leaf Int | Node (Int,Tree,Tree) subtree:: Tree -> Tree -> Bool How can i start to write this code with this data structure? Example; tree1 tree2 3 / \ 5 6 / \ 7 4 13 / \ 3 12 / \ / \ 5 6 9 6 / \ / \ 7 4 11 7 / / \ 2 3 4 ____________________________________________________________________________________ Be a better friend, newshound, and know-it-all with Yahoo! Mobile. Try it now. http://mobile.yahoo.com/;_ylt=Ahu06i62sR8HDtDypao8Wcj9tAcJ

2008/4/28 cetin tozkoparan
Assume a tree is a subtree of the other if all elements of the first tree is included in the second with the exact structure; all parent-child relations are preserved with their order.
data Tree = Empty | Leaf Int | Node (Int,Tree,Tree)
Bit of a nitpick: Haskell folks would usually leave off the tuple on the Node constructor, since constructors tuple for you already. So Tree would become: data Tree = Empty | Leaf Int | Node Int Tree Tree But it's (almost) equivalent either way.
subtree:: Tree -> Tree -> Bool
How can i start to write this code with this data structure?
The way most tree algorithms are done is by recursion. Maybe it would help if you saw the problem in a more explicit form: A tree t is a subtree of a tree u if: t = u, u is a Node and t is a subtree of the left child, or u is a Node and t is a subtree of the right child. That definition should roughly translate into an inefficient implementation. There's probably a more efficient one somewhere, but it's somewhere other than the top of my head. Luke

2008/4/28 cetin tozkoparan
Assume a tree is a subtree of the other if all elements of the first tree is included in the second with the exact structure; all parent-child relations are preserved with their order.
data Tree = Empty | Leaf Int | Node (Int,Tree,Tree) subtree:: Tree -> Tree -> Bool
Let me also point out that since you store an Int at each Node, there is no need for the explicit Leaf constructor; for example, Leaf 5 can be represented as Node 5 Empty Empty. Simplifying your data structure in this way will make writing code for it much simpler and more elegant. -Brent
participants (3)
-
Brent Yorgey
-
cetin tozkoparan
-
Luke Palmer