Question 8
Back to Exercise
What is the output of the following Java program?
public class Main {
static class Node {
int key;
Node left, right;
Node(int key) { this.key = key; }
}
static Node insert(Node n, int k) {
if (n == null) return new Node(k);
if (k < n.key) n.left = insert(n.left, k);
else n.right = insert(n.right, k);
return n;
}
static void post(Node n, StringBuilder sb) {
if (n == null) return;
post(n.left, sb);
post(n.right, sb);
sb.append(n.key).append(' ');
}
public static void main(String[] args) {
Node root = null;
for (int k : new int[]{8, 3, 10, 1, 6, 14, 4}) root = insert(root, k);
StringBuilder sb = new StringBuilder();
post(root, sb);
System.out.println(sb.toString().trim());
}
}
- A 1 3 4 6 8 10 14
- B 1 4 6 3 14 10 8 Correct
- C 8 3 1 6 4 10 14
- D 4 6 1 3 14 10 8
Correct Answer: Option B
Postorder prints both subtrees before the node, so the root 8 comes last. 4 is the left child of 6.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!