Inorder traversal is a Depth-First Traversal method where we visit nodes in the following order:
This traversal results in nodes being visited in sorted order if the tree is a Binary Search Tree (BST).
Consider the following binary tree:
4
).2
(after visiting left subtree).5
).1
(after visiting left subtree).3
).4
→ 2
→ 5
→ 1
→ 3
https://drawtocode.vercel.app/problems/binary-tree-inorder-traversal
Loading component...
Loading component...
INPUT: graph with 1,2,3,4,5 nodes
OUTPUT: 4 2 5 1 3
public static void main(String[] args) {
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
System.out.println("Inorder Traversal:");
inorder(root);
} // Function End
static void inorder(Node root) {
if (root == null){
return;
}//If End
inorder(root.left);
System.out.print(root.value + " ");
inorder(root.right);
}function end
static class TreeNode {
int val;
TreeNode left , right;
TreeNode(int val){
this.val = val;
this.left = this.right = null;
}
} // Class end