有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java是否可以将多个节点链接到单个节点?

我正试图建立一个基于链表的树结构。由于链表只能直接指向下一个节点(对于单链表),因此我想修改链表的概念。是否可以从多个节点指向一个节点

这是一幅图画

enter image description here


共 (2) 个答案

  1. # 1 楼答案

    请参见下面我的实现:

    package treeTest;
    
    public class Node {
    private Node left;
    private Node right;
    private String data;
    public Node(String data) {
        this.data = data;
        left = null;
        right = null;
    }
    
    public Node getLeft() {
        return left;
    }
    
    public void setLeft(Node left) {
        this.left = left;
    }
    
    public Node getRight() {
        return right;
    }
    
    public void setRight(Node right) {
        this.right = right;
    }
    
    public String getData() {
        return data;
    }
    
    public void setData(String data) {
        this.data = data;
    }
    

    }

    package treeTest;
    
    public class Tree {
    private Node root;
    
    public Tree() {
        root = null;
    }
    
    public void insert(String data) {
        root = insert(root, data);
    }
    
    private Node insert(Node node, String data) {
        if(node == null) {
            // Then create tree
            node = new Node(data);
        } else {
            if(data.compareTo(node.getData()) <= 0) {
                node.setLeft( insert(node.getLeft(), data));
            } else {
                node.setRight(insert(node.getRight(), data));
            }
        }
        return node;
    }
    

    }

    package treeTest;
    
    import java.util.Scanner;
    
    public class TestTree {
    
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Tree tree = new Tree();
    
        tree.insert("Hurricane");
        // Second level
        tree.insert("Cat1");
        tree.insert("Cat2");
        tree.insert("Cat3");
    }
    
    }
    

    有关更多详细信息,请查看此Java Program to Implement a Binary Search Tree using Linked Lists

  2. # 2 楼答案

    我认为以下方法可行:

    class Node {
        Node sibling;
        Node child;
        Object item;
    }
    

    同级将指向并行级别的下一个节点,子级将指向较低级别的节点