Java – construct (non binary) trees from arrays
I need to build a tree in Java I have completed the tree as the data structure But I had some problems providing data from the array to the tree This is what I need to do
domain = {"b","c"};
Then the tree should look like:
null -> b,c b->c c->b
So basically, I want the child nodes of the node to have all the child nodes from the domain that have not been overwritten The problem is that despite many attempts, I can't write code to do this I know it can be done with recursive functions I don't want complete code Any hint of a solution will be highly appreciated thank you.
Attached:
I made it clear Every node in the '' tree has all values from the child nodes of the domain, except the child node or its parent node that has been overwritten ""
As shown in the figure, a is the cardinality (such as null) It has all the values in the field (B, c) B has C, C has b
Solution
The specification says:
It's a little unclear, but I assume that it overrides it or its parent node, which means that a node with a value of X is allowed if the value x is not on the path from node to root In this case, the tree can be constructed like this (the language is Haskell):
import List data Tree = Tree String [Tree] build x xs = Tree x children where children = map (\x -> build x (delete x xs)) xs
For example, given the root value "a" and the domain value list ["B", "C", "d"), the program constructs a root node with the value "a", and recursively constructs three child nodes:
>Root value "B" and domain ["C", > root value "C" and domain ["B", > and root value "d" and domain ["B", "C"]
In pseudo python, this is the algorithm of Haskell program:
def build(root_value,domain): node = Tree(root_value) # For each value in the domain: for i in range(len(domain)): child_root = domain[i] # The child domain is equal to the original domain # with value at position 'i' removed. child_domain = domain[: i] + domain[i + 1:] # Recursively build the child child = build(child_root,child_domain) # - and add the child to the node. node.add_child(child) return node
This is a test of the build function, which prints the tree of the problem example and the above example:
pretty level (Tree x children) = do mapM_ putStr [indent,x,"\n"] mapM_ (pretty (level + 3)) children where indent = replicate level ' ' main = do putStrLn "Tree for a -> b,c:" pretty 0 (build "a" ["b","c"]) putStrLn "\nTree for a -> b,c,d:" pretty 0 (build "a" ["b","c","d"])
The test uses indentation to show the depth of each node in the tree:
Tree for a -> b,c: a b c c b Tree for a -> b,d: a b c d d c c b d d b d b c c b