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

时间:2017-10-08 22:58:46

标签: java pointers tree

我正在尝试根据链表创建树结构。由于链表只能直接指向下一个节点(对于单链表),我想修改链表的概念。是否可以从多个节点指向一个节点?

这是图中的图像

enter image description here

2 个答案:

答案 0 :(得分:0)

我认为以下内容可行:

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

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

答案 1 :(得分:0)

见下文我的实施:

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