简体   繁体   中英

A good way to populate triangle of numbers into tree data structure

I have a following data in my input file:

1
3 2
5 6 4
7 9 8 10

The relationship between the data is the following:

3 and 2 are children of 1, and 3 has children 5, 6 while 2 has children 6 and 4.

So it is a triangle-based structure, like a pyramid.

I have written a class called Tree in my code, and tree has a an object of class TriangleNode for the tree root:

public class TriangleNode { 
    public int data; 
    public TriangleNode leftChild;
    public TriangleNode rightChild;

    public Node(int item) 
    { 
        data = item; 
        leftChild = null;
        rightChild = null;
    } 
} 

What I need to do specifically, is to read the triangle and populate all the data into my own custom structure which is described above. It would be good not to duplicate objects, so if two parents share a child in a triangle do something like this (maybe). But I need to do this for a whole file.

tree.node.left.right = new TriangleNode(2);
tree.node.right.left = tree.node.left.right;

Maybe someone could help me with a way to populate my structure with a data efficiently? I looked here and didn't find a good way to do this. Thanks in advance!

Not only would it be good not to duplicate objects, but it's most probably a must too, because if one of these objects changed somehow, then you would have to ensure the other one changed too.

So I would suggest keeping a collection of data and referring to its members from your TriangleNode class, instead of creating 2 separate identical objects (one for each parent in two different parent nodes).

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