Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to print the root node's value in inorder traversal.
DSA Java
void inorder(Node node) {
if (node == null) return;
inorder(node.left);
System.out.println(node[1]);
inorder(node.right);
}Attempts:
3 left
💡 Hint
Common Mistakes
Using a field name that does not exist in the Node class.
Forgetting to print the node's value.
✗ Incorrect
In this tree node class, the value is stored in the 'data' field, so we access node.data to print the root's value.
2fill in blank
mediumComplete the code to recursively traverse the left subtree first in inorder traversal.
DSA Java
void inorder(Node node) {
if (node == null) return;
[1](node.left);
System.out.println(node.data);
inorder(node.right);
}Attempts:
3 left
💡 Hint
Common Mistakes
Calling a different traversal function like preorder or postorder.
Not calling the function recursively.
✗ Incorrect
In inorder traversal, we recursively call the same inorder function on the left child first.
3fill in blank
hardFix the error in the inorder traversal code to correctly traverse the right subtree.
DSA Java
void inorder(Node node) {
if (node == null) return;
inorder(node.left);
System.out.println(node.data);
[1](node.right);
}Attempts:
3 left
💡 Hint
Common Mistakes
Using a different traversal function for the right subtree.
Forgetting to traverse the right subtree.
✗ Incorrect
The right subtree must be traversed using the same inorder function to maintain the left-root-right order.
4fill in blank
hardFill both blanks to create a map of node values to their depths during inorder traversal.
DSA Java
void inorderDepth(Node node, int depth, Map<Integer, Integer> map) {
if (node == null) return;
inorderDepth(node[1], depth[2], map);
map.put(node.data, depth);
inorderDepth(node.right, depth + 1, map);
}Attempts:
3 left
💡 Hint
Common Mistakes
Using '.right' instead of '.left' for the left subtree.
Decreasing depth instead of increasing it.
✗ Incorrect
We traverse the left child with depth increased by 1 to track depth correctly.
5fill in blank
hardFill all three blanks to build a list of node values in inorder traversal.
DSA Java
void inorderList(Node node, List<Integer> list) {
if (node == null) return;
inorderList(node[1], list);
list.[2](node.data);
inorderList(node[3], list);
}Attempts:
3 left
💡 Hint
Common Mistakes
Using 'append' which is not a Java List method.
Mixing up left and right child accesses.
✗ Incorrect
We traverse left child, add current node's data to list, then traverse right child.
