How to implement a tree data-structure in Java?

前端 未结 24 2456
鱼传尺愫
鱼传尺愫 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条回答
  •  -上瘾入骨i
    2020-11-22 01:02

        // TestTree.java
    // A simple test to see how we can build a tree and populate it
    //
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    
    public class TestTree extends JFrame {
    
      JTree tree;
      DefaultTreeModel treeModel;
    
      public TestTree( ) {
        super("Tree Test Example");
        setSize(400, 300);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
      }
    
      public void init( ) {
        // Build up a bunch of TreeNodes. We use DefaultMutableTreeNode because the
        // DefaultTreeModel can use it to build a complete tree.
        DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
        DefaultMutableTreeNode subroot = new DefaultMutableTreeNode("SubRoot");
        DefaultMutableTreeNode leaf1 = new DefaultMutableTreeNode("Leaf 1");
        DefaultMutableTreeNode leaf2 = new DefaultMutableTreeNode("Leaf 2");
    
        // Build our tree model starting at the root node, and then make a JTree out
        // of it.
        treeModel = new DefaultTreeModel(root);
        tree = new JTree(treeModel);
    
        // Build the tree up from the nodes we created.
        treeModel.insertNodeInto(subroot, root, 0);
        // Or, more succinctly:
        subroot.add(leaf1);
        root.add(leaf2);
    
        // Display it.
        getContentPane( ).add(tree, BorderLayout.CENTER);
      }
    
      public static void main(String args[]) {
        TestTree tt = new TestTree( );
        tt.init( );
        tt.setVisible(true);
      }
    }
    

提交回复
热议问题