在使用链表的java中的二进制树

时间:2016-04-28 19:08:13

标签: java binary-tree binary-search-tree

我想知道我是否可以使用链表创建二叉树。 在每个节点中,有一个较小的链表来保存该特定节点的信息。 我正在寻找关于如何使每个节点保持另一个链表的提示。这是作业。

3 个答案:

答案 0 :(得分:1)

如果您希望树节点数据作为链表而不是整数,那么您可以使用此

public class Tree {
    static class LinkedList{
        int data;
        LinkedList next;
        public LinkedList(int data, LinkedList next){
            this.data = data;
            this.next = next;
        }
    }
    LinkedList node;
    Tree left;
    Tree right;
    public Tree(LinkedList node, Tree left, Tree right){
        this.node = node;
        this.left = left;
        this.right = right;

    }
    public static void main(String[] args) {
        LinkedList l3 = new LinkedList(3,null);
        Tree node3 = new Tree(l3,null, null);//left child
        LinkedList l4 = new LinkedList(4,null);
        Tree node4 = new Tree(l4,null, null);//right child
        LinkedList l1 = new LinkedList(1,null);
        LinkedList l2 = new LinkedList(2, l1);
        Tree node1 = new Tree(l2,node3, node4);//node1 be the root of tree
    }
}

这里树的每个节点都将保存一个链表。

答案 1 :(得分:0)

LinkedList和Binary搜索树Difference between a LinkedList and a Binary Search Tree之间存在差异。 BST的原则被称为'组合'。例如组成≠继承Difference between Inheritance and Composition。 二进制搜索树只是用于存储的有序二叉树 组成项目。因为它是二进制文件,所以您可以在每个节点中向左或向右移动。因此,每个节点对象应该具有leftNoderightNode作为组合。 这应该让你开始自己做功课。

答案 2 :(得分:-2)

你能看出这是否能回答你的问题?我是从geeksforgeeks.org

的另一个人那里得到的
/*
The structure of Link list node is as follows 
struct node
{
    int data;
    struct node* next;
};

The structure of TreeNode is as follows
struct TreeNode
{
    int data;
    TreeNode *left;
    TreeNode *right;
};
*/

TreeNode* newTreeNode(int data)
{
    TreeNode *temp = new TreeNode;
    temp->data = data;
    temp->left = temp->right = NULL;
    return temp;
}
/*You are required to complete this method*/
void convert(node *head,TreeNode * &root)
{
 queue<TreeNode *> q;
    root=newTreeNode(head->data);
    head=head->next;
    q.push(root);
    while(!q.empty()){
        TreeNode *tmp=q.front();
        q.pop();
        if(head){
            tmp->left=newTreeNode(head->data);
            q.push(tmp->left);
            head=head->next;
        }
        if(head){
            tmp->right=newTreeNode(head->data);
            q.push(tmp->right);
            head=head->next;
        }
        if(!head)
            break;
    }

}
相关问题