-1

I recently started college with no previous coding experience. I began to study a tree data structure and its Java implementation. The question is quite basic but I have not found an answer to it.

As in a list you'd start by typing import java.util.List what do you need to do in order to start with a tree implementation?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197

4 Answers4

1

There is no need to import a Java package for implementing Trees. Tree structure is a collection of nodes/instance of a class referencing to the address of the child nodes. Although, there are different types of trees like Binary Search Tree or AVL Trees, however each tree has separate property.

Sample Implementation of Binary Search Tree in Java is as follows:

/* Node Class containing left and right child of current
node and key value*/
class Node
{
    int key;
    Node left, right;

    public Node(int item)
    {
        key = item;
        left = right = null;
    }
}

class Tree
{
    Node root;

    Tree()
    {
        root = null;
    }

    public static void main(String[] args)
    {
        Tree tree = new Tree();
        tree.root = new Node(1);
        tree.root.left = new Node(2);
        tree.root.right = new Node(3);
        tree.root.left.left = new Node(4);
    }
}

Vidip
  • 162
  • 1
  • 2
  • 13
0

The easiest answer is the DefaultTreeModel class. Basically, you create TreeNode objects and add them to the Model or Parent node as needed. DefaultMutableTreeNode should be good enough to meet your needs as a beginner.

You can navigate the model using recursion easily enough.

Ryan
  • 1,762
  • 6
  • 11
  • This is a swing class. I don't recommend using swing if you just need to implement a simple data structure. – cwittah Apr 14 '21 at 19:56
  • It's a swing class, but the model is sound and can easily be used outside of swing. – Ryan Apr 14 '21 at 19:57
0

For a regular binary tree you could implement your own:

class Node {
    int value;
    Node left;
    Node right;

    public Node(int value) {
        this.value = value;
    }
}

Then create a BinaryTree class that contains a root Node instance.

cwittah
  • 349
  • 1
  • 3
  • 17
0

a tree structure is a bit different from the list implementation...

i recommend you to see this topic if you just want the code, if your focus question isn't how to do if but how does they work, i recommend this.

and if you have found the problem by using this data structure, you need to learn this