In the field of data structures, determining the height of a tree is a common task. The height of a tree is defined as the length of the longest path from the root node to any leaf node. In this tutorial, we will explore various methods to find the height of a tree in Java.
Method 1: Recursive Approach
To find the height of a tree recursively, we can utilize the concept of depth-first traversal. We start by checking if the tree is empty or not.
- If the tree is empty, then its height is 0.
- If the tree is not empty, then we recursively calculate the heights of its left and right subtrees.
Let’s take a look at an implementation:
public class TreeHeight {
public static int getHeight(TreeNode root) {
if (root == null) {
return 0;
}
int leftHeight = getHeight(root.left);
int rightHeight = getHeight(root.right);
return Math.max(leftHeight, rightHeight) + 1;
}
}
The above code defines a class TreeHeight with a static method getHeight(). This method takes in a parameter root, which represents the root node of the tree.
If the root node is null, indicating an empty tree, it returns 0. Otherwise, it recursively calculates and returns the maximum height between its left and right subtrees plus one.
Example Usage:
TreeNode root = new TreeNode(10);
root.left = new TreeNode(5);
root.right = new TreeNode(15);
root.right.left = new TreeNode(12);
int height = TreeHeight.getHeight(root);
System.out.println("Height of the tree: " + height);
The above code creates a binary tree with the given structure:
10 / \ 5 15 / 12
Running the code will output:
Height of the tree: 3
Method 2: Iterative Approach using Queue
Another way to find the height of a tree is by using an iterative approach with the help of a queue. We can perform a level order traversal and keep track of each level. The number of levels will be equal to the height of the tree.
import java.util.LinkedList;
import java.Queue;
public class TreeHeight {
public static int getHeight(TreeNode root) {
if (root == null) {
return 0;
}
Queue queue = new LinkedList<>();
queue.offer(root);
int height = 0;
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
TreeNode node = queue.poll();
if (node.left != null) {
queue.offer(node.left);
}
if (node.right != null) {
queue.right);
}
}
height++;
}
return height;
}
}
The above code defines a class TreeHeight with a static method getHeight(). Otherwise, it performs a level order traversal using a queue and increments the height after each level. The final height is returned.
The above code creates the same binary tree as in the previous example and outputs:
Both methods described above are efficient ways to find the height of a tree in Java. You can choose either method based on your preference or requirement.
In conclusion, determining the height of a tree is an important task in data structures. By applying recursive or iterative approaches, we can easily calculate the height of a given tree using Java programming.