简体   繁体   English

在java中添加任何节点的树

[英]tree in java to add any no of nodes

i want to build a tree in java. 我想在java中构建一个树。 operations such as insert delete update. 插入删除更新等操作。 how to go about it? 怎么去呢? I dont want a binary tree, i want to add children based on user input 我不想要二叉树,我想根据用户输入添加孩子

i have implemented the following 我已经实现了以下内容

import java.util.ArrayList;


public class Tree {

private Node root;

public Tree(String rootData)
{
    root=new Node();
    root.data=rootData;
    root.children=new ArrayList<Node>();
}

public void addChild(String name)
{

}
}

import java.util.*;

class Node { 
      String data;
      Node parent;
     List<Node> children;

 public Node()
 {
     data=null;
     children=null;
     parent=null;
 }
 public Node(String name)
 {
   Node n=new Node(name);
   n.data=name;
   n.children=new ArrayList<Node>();
 }

} }

Not entirely sure what you want. 不完全确定你想要什么。 You might want to look into the DefaultTreeModel implementation or the TreeModel interface for the JTree, perhaps. 您可能希望查看DefaultTreeModel实现或JTree的TreeModel接口。 No need to reinvent the wheel. 无需重新发明轮子。 More often than not the wheel will look distinctly triangular. 通常情况下,车轮看起来会明显呈三角形。

Anyway , this might help a bit: 无论如何 ,这可能有点帮助:

import java.util.ArrayList;


public class Tree {
    private Node root;

    public Tree(String rootData)
    {
        root=new Node();
        root.data=rootData;
        root.children=new ArrayList<Node>();
    }

    public List<Node> getPathToNode(Node node) {
        Node currentNode = node;
        List<Node> reversePath = new ArrayList<Node>();
        reversePath.add(node);
        while (!(this.root.equals(currentNode)) {
            currentNode = currentNode.getParentNode();
            reversePath.add(currentNode);
        }
        Collections.reverse(reversePath); // now the list is root -> node
        return reversePath;              
    }

}

import java.util.*;

class Node { 
    String data;
    Node parent;
    List<Node> children;

    /* I would remove this constructor or at least initialize the field to non-null defaults. This is bloody dangerous. */
    public Node()
    {
        data=null;
        children=null;
        parent=null;
    }

    public Node(String name)
    {
        Node n=new Node(name);
        n.data=name;
        n.children=new ArrayList<Node>();
    }

    public void addChild(String name) {
        this.addChild(new Node(name));
    }

    public void addChild(Node child) {
        this.children.add(child);
    }

    public void removeChild(Node child) {
        this.children.remove(child);
    }

    public void removeChild(String name) {
        this.removeChild(this.getChild(name));
    }

    public Node getChild(int childIndex) {
        return this.children.get(childIndex);
    }

    public Node getChild(String childName) {
        for (Node child : this.children) {
            if (child.getName().equals(childName)) { return child; }
        }
        return null;
    }

    public Node getParentNode() {
        return this.parent;
    }
} 

Here is the solution 这是解决方案

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;


public class MyTree extends JFrame{

private JTree tree;
private DefaultTreeModel model;
private DefaultMutableTreeNode rootNode;


public MyTree()
{
     DefaultMutableTreeNode philosophersNode = getTree();
        model = new DefaultTreeModel(philosophersNode);
        tree = new JTree(model);
        JButton addButton = new JButton("Add ");
        addButton.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent event) {
            addNode();
          }
        });
        JButton removeButton = new JButton("Delete");
        removeButton.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent event) {
              removeSelectedNode();
          }
        });
        JPanel inputPanel = new JPanel();
        inputPanel.add(addButton);
        inputPanel.add(removeButton);

        Container container = getContentPane();

        container.add(new JScrollPane(tree), BorderLayout.CENTER);

        container.add(inputPanel, BorderLayout.NORTH);

        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setSize(400, 500);
        setVisible(true);

}

 private DefaultMutableTreeNode getSelectedNode() {

        return (DefaultMutableTreeNode)   tree.getLastSelectedPathComponent();
      }

 private DefaultMutableTreeNode getTree() {
         rootNode = new DefaultMutableTreeNode("Root");
        return rootNode;
      }

 private void removeSelectedNode() {
        DefaultMutableTreeNode selectedNode = getSelectedNode();
        if (selectedNode != null){
             if(selectedNode.toString()=="Root")
                {
                     JOptionPane.showMessageDialog(MyTree.this, "Cannot delete root element", "Error",
                              JOptionPane.ERROR_MESSAGE);
                }else{

          model.removeNodeFromParent(selectedNode);
                }
        }

      }

 private void addNode() {
        DefaultMutableTreeNode parent = getSelectedNode();
        if (parent == null) {
          JOptionPane.showMessageDialog(MyTree.this, "Select an area.",   "Error",
              JOptionPane.ERROR_MESSAGE);

          return;
        }
        String name = JOptionPane.showInputDialog(MyTree.this, "Enter Name:");
        model.insertNodeInto(new DefaultMutableTreeNode(name), parent,     parent.getChildCount());

      }

 public static void main(String args[]) {
        new MyTree();
      }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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