azarazlan
azarazlan

Reputation: 29

Java n-node tree

I'm trying to write Java code for the following figure. Where,

if node:4 will create following separate 4 trees. Number of node in

LEVEL1 (yellow) : 1 node
LEVEL2 (green) : n-1 node
LEVEL3 (blue) : n-2 node

see image for node:4

enter image description here

Another way if node : 5 then,

LEVEL1 (yellow) : 1 node
LEVEL2 (green) : n-1 node
LEVEL3 (blue) : n-2 node

see image for node:5

enter image description here

And so on. Thanks in advance for kind help.

Upvotes: 2

Views: 147

Answers (1)

Joop Eggen
Joop Eggen

Reputation: 109595

How to solve is what is important here. Start top-down, and work out the logic.

List<Tree> makeTrees(int n) {
    List<Tree> trees = new ArrayList<>();

    for (int i = 0; i < n; ++i) {
        Tree tree = makeYellow(n, i);
        trees.add(tree);
    }
    return trees;
}

private Tree makeYellow(int n, int yellow) {
    Tree tree = new Tree();
    Node node = new Node(yellow, Color.YELLOW);
    tree.add(node);
    for (int i = 0; i < n; ++i) {
        if (i != yellow) {
            Node green = makeGreen(n, yellow, i);
            node.add(green);
        }
    }
    return tree;
}

And so on.

As you see, at the top for the yellow nodes a simple for suffices. Instead of already working everything out in detail, anticipate the further solution, call makeGreen and determine what it should return and what info it needs.

Try to find patterns.

Such homework is best done oneself in order to train solving such puzzles, and being mentally rewarded.

Upvotes: 1

Related Questions