Which of the following best explains why trees are preferred over arrays or linked lists for representing hierarchical data?
Think about how data is connected in a family tree or folder structure.
Trees naturally represent hierarchical relationships with nodes having multiple children, unlike arrays or linked lists which are linear structures.
Consider the following Java code snippets representing a simple tree node and a linked list node. What is the printed output after connecting nodes?
class TreeNode { int val; TreeNode left, right; TreeNode(int val) { this.val = val; } } class ListNode { int val; ListNode next; ListNode(int val) { this.val = val; } } public class Main { public static void main(String[] args) { TreeNode root = new TreeNode(1); root.left = new TreeNode(2); root.right = new TreeNode(3); ListNode head = new ListNode(1); head.next = new ListNode(2); head.next.next = new ListNode(3); System.out.println("Tree root: " + root.val + ", left: " + root.left.val + ", right: " + root.right.val); System.out.print("Linked list: "); ListNode current = head; while(current != null) { System.out.print(current.val + " -> "); current = current.next; } System.out.println("null"); } }
Trace the assignments of left, right, and next pointers carefully.
The tree nodes are connected with left and right children as 2 and 3 respectively. The linked list nodes are connected linearly as 1 -> 2 -> 3 -> null.
Given the following Java code for a tree traversal, why does it fail to print all nodes?
class TreeNode { int val; TreeNode left, right; TreeNode(int val) { this.val = val; } } public class Main { public static void inorder(TreeNode node) { if (node == null) return; inorder(node.left); System.out.print(node.val + " "); // Missing right subtree traversal } public static void main(String[] args) { TreeNode root = new TreeNode(1); root.left = new TreeNode(2); root.right = new TreeNode(3); inorder(root); } }
Check if all recursive calls cover both left and right children.
The inorder traversal must visit left subtree, then node, then right subtree. The code misses the call to traverse the right subtree.
Which option correctly fixes the syntax error in the following Java class?
class TreeNode {
int val
TreeNode left, right;
TreeNode(int val) { this.val = val; }
}Look carefully at each line's punctuation.
In Java, each variable declaration must end with a semicolon. Missing semicolon after 'int val' causes a syntax error.
Which statement best explains why trees (like binary search trees) are essential for faster searching compared to arrays and linked lists?
Consider how binary search works and how trees split data.
Binary search trees allow searching by comparing and moving left or right, reducing search time to O(log n). Arrays and linked lists require scanning elements one by one, O(n).
