ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

Binary Search Tree (BST) - In-order Traversal

Java

Goal -- WPM

Ready
Exercise Algorithm Area
1import java.util.ArrayList;
2import java.util.List;
3
4// Definition for a binary tree node.
5class TreeNode {
6int val;
7TreeNode left;
8TreeNode right;
9
10TreeNode() {}
11TreeNode(int val) { this.val = val; }
12TreeNode(int val, TreeNode left, TreeNode right) {
13this.val = val;
14this.left = left;
15this.right = right;
16}
17}
18
19public class BinarySearchTreeInOrder {
20
21/**
22* Performs an in-order traversal of a Binary Search Tree (BST).
23* In-order traversal visits nodes in the order: left subtree, root, right subtree.
24* For a BST, this results in visiting nodes in ascending order of their values.
25*
26* @param root The root node of the BST.
27* @return A list of integers representing the node values in in-order sequence.
28*/
29public List<Integer> inorderTraversal(TreeNode root) {
30List<Integer> result = new ArrayList<>();
31// Handle the edge case of an empty tree.
32if (root == null) {
33return result; // Return an empty list for an empty tree.
34}
35// Call the recursive helper function to perform the traversal.
36inorderTraversalHelper(root, result);
37return result;
38}
39
40/**
41* Recursive helper function for in-order traversal.
42*
43* @param node The current node being visited.
44* @param result The list to which visited node values are added.
45*/
46private void inorderTraversalHelper(TreeNode node, List<Integer> result) {
47// Base case: If the current node is null, we stop recursion for this path.
48if (node == null) {
49return;
50}
51
52// 1. Traverse the left subtree recursively.
53// This ensures all nodes in the left subtree are visited before the current node.
54inorderTraversalHelper(node.left, result);
55
56// 2. Visit the current node.
57// Add the value of the current node to the result list.
58result.add(node.val);
59
60// 3. Traverse the right subtree recursively.
61// This ensures all nodes in the right subtree are visited after the current node.
62inorderTraversalHelper(node.right, result);
63}
64
65// Helper method to build a sample BST for testing.
66// This is a simplified BST construction and does not balance the tree.
67public static TreeNode insertIntoBST(TreeNode root, int val) {
68if (root == null) {
69return new TreeNode(val);
70}
71if (val < root.val) {
72root.left = insertIntoBST(root.left, val);
73} else if (val > root.val) {
74root.right = insertIntoBST(root.right, val);
75}
76// If val is equal, we do nothing (no duplicates in this simple BST).
77return root;
78}
79
80public static void main(String[] args) {
81// Example 1: A simple BST
82TreeNode root1 = null;
83root1 = insertIntoBST(root1, 4);
84root1 = insertIntoBST(root1, 2);
85root1 = insertIntoBST(root1, 5);
86root1 = insertIntoBST(root1, 1);
87root1 = insertIntoBST(root1, 3);
88
89BinarySearchTreeInOrder bstTraversal1 = new BinarySearchTreeInOrder();
90List<Integer> inorder1 = bstTraversal1.inorderTraversal(root1);
91System.out.println("In-order traversal 1: " + inorder1); // Expected: [1, 2, 3, 4, 5]
92
93// Example 2: An empty tree
94TreeNode root2 = null;
95BinarySearchTreeInOrder bstTraversal2 = new BinarySearchTreeInOrder();
96List<Integer> inorder2 = bstTraversal2.inorderTraversal(root2);
97System.out.println("In-order traversal 2: " + inorder2); // Expected: []
98
99// Example 3: A tree with only a root node
100TreeNode root3 = new TreeNode(10);
101BinarySearchTreeInOrder bstTraversal3 = new BinarySearchTreeInOrder();
102List<Integer> inorder3 = bstTraversal3.inorderTraversal(root3);
103System.out.println("In-order traversal 3: " + inorder3); // Expected: [10]
104
105// Example 4: A skewed tree (left skewed)
106TreeNode root4 = null;
107root4 = insertIntoBST(root4, 5);
108root4 = insertIntoBST(root4, 4);
109root4 = insertIntoBST(root4, 3);
110root4 = insertIntoBST(root4, 2);
111root4 = insertIntoBST(root4, 1);
112BinarySearchTreeInOrder bstTraversal4 = new BinarySearchTreeInOrder();
113List<Integer> inorder4 = bstTraversal4.inorderTraversal(root4);
114System.out.println("In-order traversal 4: " + inorder4); // Expected: [1, 2, 3, 4, 5]
115
116// Example 5: A skewed tree (right skewed)
117TreeNode root5 = null;
118root5 = insertIntoBST(root5, 1);
119root5 = insertIntoBST(root5, 2);
120root5 = insertIntoBST(root5, 3);
121root5 = insertIntoBST(root5, 4);
122root5 = insertIntoBST(root5, 5);
123BinarySearchTreeInOrder bstTraversal5 = new BinarySearchTreeInOrder();
124List<Integer> inorder5 = bstTraversal5.inorderTraversal(root5);
125System.out.println("In-order traversal 5: " + inorder5); // Expected: [1, 2, 3, 4, 5]
126}
127}
Algorithm description viewbox

Binary Search Tree (BST) - In-order Traversal

Algorithm description:

This Java code demonstrates the in-order traversal of a Binary Search Tree (BST). In-order traversal visits nodes in a specific order: first the left subtree, then the current node, and finally the right subtree. For a BST, this traversal visits the nodes in ascending order of their values, making it useful for tasks like sorting or retrieving sorted data.

Algorithm explanation:

The `inorderTraversal` method initializes an empty list to store the results and calls a recursive helper function `inorderTraversalHelper`. The helper function takes the current node and the result list as arguments. The base case for the recursion is when a node is null, at which point the function returns. Otherwise, it first recursively calls itself on the left child, then adds the current node's value to the result list, and finally recursively calls itself on the right child. This order ensures that all nodes in the left subtree are processed before the current node, and all nodes in the right subtree are processed after. The time complexity is O(N), where N is the number of nodes in the tree, because each node is visited exactly once. The space complexity is O(H) in the average case (balanced tree) and O(N) in the worst case (skewed tree) due to the recursion stack depth, plus O(N) for storing the result list.

Pseudocode:

function inorderTraversal(root):
  result_list = empty list
  if root is null:
    return result_list
  call inorderTraversalHelper(root, result_list)
  return result_list

function inorderTraversalHelper(node, result_list):
  if node is null:
    return
  // Traverse left subtree
  inorderTraversalHelper(node.left, result_list)
  // Visit current node
  add node.val to result_list
  // Traverse right subtree
  inorderTraversalHelper(node.right, result_list)