Java Binary Tree Tutorial
Every node in a binary has at most two child nodes. Usually, each node is simply called the left and right node. While the Java programming language does not provide any built-in binary tree data structure, it is easy to create one yourself using the standard Java classes. Most binary tree data structures support some basic common operations such as creating a new empty tree, finding an existing node and inserting a node in the tree.
Instructions
-
-
1
Open Notepad. Type the following lines of codes in the Notepad window:
public class BinaryTree {
private Node root;
private static class Node {
Node left;
Node right;
int data;
Node(int newData) {
left = null;
right = null;
data = newData;
}
}
public void BinaryTree() {
root = null;
}
}
This creates a basic binary tree class in Java consisting of a root node.
-
2
Add the following lines of codes at the end of the BinaryTree class, before the final closing curly bracket:
public boolean lookup(int data) {
return(lookup(root, data));
}
private boolean lookup(Node node, int data) {
if (node==null) {
return(false);
}
if (data==node.data) {
return(true);
}
else if (data<node.data) {
return(lookup(node.left, data));
}
else {
return(lookup(node.right, data));
}
}
This allows you to use a "lookup()" method, which you can use to find a node containing the specified data in the binary tree.
-
-
3
Type the following lines of codes inside the BinaryTree class:
public void insert(int data) {
root = insert(root, data);
}
private Node insert(Node node, int data) {
if (node==null) {
node = new Node(data);
}
else {
if (data <= node.data) {
node.left = insert(node.left, data);
}
else {
node.right = insert(node.right, data);
}
}
}
This creates an "insert()" method, which you can use to insert a new node into the binary tree.
-
1
References
- Photo Credit Jupiterimages/Photos.com/Getty Images