How to implement a tree data-structure in Java?

前端 未结 24 2460
鱼传尺愫
鱼传尺愫 2020-11-22 00:27

Is there any standard Java library class to represent a tree in Java?

Specifically I need to represent the following:

  • The sub-tree at any node can have
24条回答
  •  盖世英雄少女心
    2020-11-22 00:55

    Yet another tree structure:

    public class TreeNode implements Iterable> {
    
        T data;
        TreeNode parent;
        List> children;
    
        public TreeNode(T data) {
            this.data = data;
            this.children = new LinkedList>();
        }
    
        public TreeNode addChild(T child) {
            TreeNode childNode = new TreeNode(child);
            childNode.parent = this;
            this.children.add(childNode);
            return childNode;
        }
    
        // other features ...
    
    }
    

    Sample usage:

    TreeNode root = new TreeNode("root");
    {
        TreeNode node0 = root.addChild("node0");
        TreeNode node1 = root.addChild("node1");
        TreeNode node2 = root.addChild("node2");
        {
            TreeNode node20 = node2.addChild(null);
            TreeNode node21 = node2.addChild("node21");
            {
                TreeNode node210 = node20.addChild("node210");
            }
        }
    }
    

    BONUS
    See fully-fledged tree with:

    • iterator
    • searching
    • Java/C#

    https://github.com/gt4dev/yet-another-tree-structure

提交回复
热议问题