Which of the following is a key reason trees are used instead of arrays or linked lists?
Think about how quickly you can find an item in a sorted list versus a tree.
Trees, especially binary search trees, allow searching in O(log n) time by dividing data into branches, which is faster than linear search in linked lists or arrays.
What is the output of the following JavaScript code that traverses a simple binary tree and an array?
class Node { constructor(value) { this.value = value; this.left = null; this.right = null; } } const root = new Node(1); root.left = new Node(2); root.right = new Node(3); function inorder(node) { if (!node) return []; return [...inorder(node.left), node.value, ...inorder(node.right)]; } const arr = [1, 2, 3]; console.log(inorder(root)); console.log(arr);
Inorder traversal visits left child, then node, then right child.
The inorder traversal of the tree visits nodes in the order 2, 1, 3. The array remains in its original order.
Consider this linked list code trying to represent a family tree. Why does it fail to represent the hierarchy properly?
class ListNode { constructor(value) { this.value = value; this.next = null; } } const head = new ListNode('Grandparent'); head.next = new ListNode('Parent'); head.next.next = new ListNode('Child'); // Trying to represent family tree with linked list
Think about how family trees branch out compared to a single line.
Linked lists connect nodes in a single line, so they cannot represent branching structures like trees.
What is the output of the following JavaScript code that searches for the number 5 in an array and a binary search tree?
const arr = [1, 3, 5, 7, 9]; class TreeNode { constructor(value) { this.value = value; this.left = null; this.right = null; } } const root = new TreeNode(7); root.left = new TreeNode(3); root.right = new TreeNode(9); root.left.left = new TreeNode(1); root.left.right = new TreeNode(5); function searchArray(arr, target) { for (let i = 0; i < arr.length; i++) { if (arr[i] === target) return true; } return false; } function searchTree(node, target) { if (!node) return false; if (node.value === target) return true; if (target < node.value) return searchTree(node.left, target); else return searchTree(node.right, target); } console.log(searchArray(arr, 5)); console.log(searchTree(root, 5));
Both array and tree contain the number 5.
The number 5 is found in both the array and the tree, so both searches return true.
Which statement best explains why trees are preferred over arrays and linked lists for hierarchical data?
Think about how family trees or company structures branch out.
Trees allow each node to have multiple children, which matches the branching nature of hierarchical data, unlike arrays or linked lists which are linear.