Binary Tree
Binary Tree is a data structure to store hierarchical data where each node has only two leaf nodes.
Binary Tree using Nodes
The basic building block of binary tree is a node that hold references to left and right nodes.
class TreeNode<T> {
T value;
TreeNode left;
TreeNode right;
public TreeNode(T value) {
this.value = value;
}
}Then we create a class that holds the root and provide operations over the binary tree.
class BinaryTree<T> {
TreeNode<T> root;
public String asString(TreeNode<T> node, int level) {
if (node == null) return "";
String value = level + ": " + node.value.toString() + "\n";
if (node.left != null) {
value += asString(node.left, level + 1);
}
if (node.right != null) {
value += asString(node.right, level + 1);
}
return value;
}
public String toString() {
return asString(root, 0);
}
}Now we can try to use it and print out how the tree looks like.
Here is the output.
Binary Tree using Array
An alternative to represent trees using node is to keep the values in array. Root element is stored on 0th position, left is stored on 0th + 1 position and right is stored on 0th + 2 position. If a position of element is i, then left is on 2*i+1 and right is on 2*i+2. For 0th element, it is 0*2+1 and 0*2+2. For the left element on 0th position, it is 2*1+1 and 2*1+2.

Here is an implementation of binary tree that stores and obtains elements from binary tree.
Here is the output.
Here is the output.
Balanced & Unbalanced Trees
A balanced binary tree has the minimum possible maximum height (a.k.a. depth).
Last updated
Was this helpful?