Complete the code to print the root node's value first in preorder traversal.
void preorder(Node node) {
if (node == null) return;
System.out.println(node[1]);
}The preorder traversal prints the root node's data first. The node's value is stored in the data field.
Complete the code to recursively traverse the left subtree in preorder.
void preorder(Node node) {
if (node == null) return;
System.out.println(node.data);
preorder(node[1]);
}In preorder traversal, after visiting the root, we visit the left subtree by calling preorder(node.left).
Fix the error in the code to correctly traverse the right subtree in preorder.
void preorder(Node node) {
if (node == null) return;
System.out.println(node.data);
preorder(node.left);
preorder(node[1]);
}After traversing the left subtree, preorder traversal visits the right subtree using preorder(node.right).
Fill both blanks to complete the preorder traversal method that prints root, left, then right.
void preorder(Node node) {
if (node == null) return;
System.out.println(node[1]);
preorder(node[2]);
preorder(node.right);
}The method prints the root's data, then recursively traverses the left subtree using node.left, and finally the right subtree.
Fill all three blanks to complete the preorder traversal method that prints root, left, then right subtree.
void preorder(Node node) {
if (node == null) return;
System.out.println(node[1]);
preorder(node[2]);
preorder(node[3]);
}The preorder traversal prints the root's data, then recursively visits the left subtree (node.left), and finally the right subtree (node.right).
