简体   繁体   中英

How to add multiple child nodes to a tree

I'm working on a project to create a tree with more than 2 child nodes. I get that when creating a binary tree, we can just create a left node and a right node to act as children, but when I've looked online for help in creating a tree, every solution I've found talks about creating a binary tree. I understand that part of creating a tree means you need to create an array or arraylist of children nodes, but I don't understand how I'm going to put data into that array or how I'm going to 'connect' the array of children nodes to my parent node?

Here's the code I have at the moment. I know it's not a lot, but I'm struggling just starting this project.

class Node
{
    public int data; //data for storage
    public Node[] children;//array will keep children
    public Node parent;//parent to start the tree

    public Node(, int data)//constructor will store data and children(I think?)
    {
    }
}

public class Tree //main class will implement everything in Node
{
}

How and where do I start this process of connecting my children nodes to my parent/root node?

Storing children in list not to have problems with array recreation, but you can use array too. You may also init array directly in the constructor, or when adding first child.

public class Main {

    public static void main(String[] args) {
        Node node = new Node(1)
            .addChild(new Node(2)
                    .addChild(new Node(4))
                    .addChild(new Node(5)))
            .addChild(new Node(3));
    }
}

class Node {
    public int data; //data for storage
    public List<Node> children;//array will keep children
    public Node parent;//parent to start the tree

    public Node(int data) {
        children = new ArrayList<>();
        this.data = data;
    }

    public Node addChild(Node node) {
        children.add(node);
        node.parent = this;
        return this;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM