Consider a tree where each node has a value and up to two children (left and right). The traversal visits nodes in this order: root, left child, right child.
What is the output sequence of node values for the tree below?
10 / \ 5 15 / / \ 3 12 20
def preorder(node): if node is None: return [] return [node.value] + preorder(node.left) + preorder(node.right) # Tree structure: # Node(10, left=Node(5, left=Node(3)), right=Node(15, left=Node(12), right=Node(20))) # Call preorder(root)
Preorder traversal visits the root node first, then recursively visits the left subtree, then the right subtree.
The preorder traversal visits nodes in the order: root, left subtree, right subtree. Starting at 10, then 5, then 3, then back up to 15, then 12, then 20.
Which of the following statements correctly describes a binary search tree (BST)?
Think about the ordering rule that defines a binary search tree.
A binary search tree requires that for each node, all values in the left subtree are less than the node's value, and all values in its right subtree are greater. This property allows efficient searching.
Given the same binary tree, which traversal method produces the nodes in ascending order if the tree is a binary search tree?
Consider which traversal visits nodes in sorted order for a BST.
Inorder traversal visits the left subtree, then the root, then the right subtree. For a BST, this results in nodes being visited in ascending order.
Consider the following pseudocode for inserting a value into a binary search tree:
function insert(node, value):
if node is None:
return new Node(value)
if value < node.value:
insert(node.left, value)
else:
insert(node.right, value)
return nodeWhat is the main problem with this code?
Think about how recursive calls affect the tree structure and what must be done to keep the tree updated.
The recursive calls insert the new node but do not assign the returned node to the parent's left or right pointer, so the tree structure does not update correctly.
Given the following tree structure, what is the height of the tree?
A
/ \
B C
/ / \
D E F
/ \
G H
\
IHeight is defined as the number of edges on the longest path from the root to a leaf.
Trace the longest path from root A to the deepest leaf node.
The longest path is A -> C -> F -> H -> I, which has 4 edges, so the height is 4.