Binary tree (Array implementation) in java

class BinaryTree {
  private int[] tree;

  public BinaryTree(int size) {
    this.tree = new int[size];
  }

  public void insert(int data, int index) {
    this.tree[index] = data;
  }

  public int leftChild(int index) {
    return this.tree[2 * index + 1];
  }

  public int rightChild(int index) {
    return this.tree[2 * index + 2];
  }

  public int parent(int index) {
    return this.tree[(index - 1) / 2];
  }
}

the BinaryTree class has a private integer array named tree that represents the nodes of the tree. The constructor takes an integer parameter size that determines the size of the array. The insert method is used to insert a new node with a specified data and index. The leftChild, rightChild, and parent methods return the left child, right child, and parent node of a given node index, respectively.

This is just a basic example of how you can implement a binary tree using an array in Java. There are many other ways to implement binary trees, including using linked lists or objects.

Submit Your Programming Assignment Details