-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinaryTreeInorder.java
More file actions
32 lines (28 loc) · 984 Bytes
/
BinaryTreeInorder.java
File metadata and controls
32 lines (28 loc) · 984 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import java.util.ArrayList;
import java.util.List;
class Solution {
public static void main(String[] args) {
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
root.left.right = new TreeNode(5);
// Calling preorderTraversal method
List<Integer> inorderList = inorderTraversal(root);
// Printing the result
System.out.println("Inorder traversal: " + inorderList);
}
public static List<Integer> inorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<>();
inorder(root, result);
return result;
}
private static void inorder(TreeNode node, List<Integer> result) {
if (node == null) {
return;
}
inorder(node.left, result);
result.add(node.val); // Add the value to the result list
inorder(node.right, result);
}
}