Consider the following binary tree structure and code to calculate its height. What will be the output?
class Node { val: number; left: Node | null; right: Node | null; constructor(val: number) { this.val = val; this.left = null; this.right = null; } } function height(root: Node | null): number { if (!root) return 0; return 1 + Math.max(height(root.left), height(root.right)); } const root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); console.log(height(root));
Height counts the number of nodes on the longest path from root to leaf.
The longest path is from root (1) to leaf (4 or 5) with 3 nodes, so height is 3.
What is the output of the height function for this skewed binary tree?
class Node { val: number; left: Node | null; right: Node | null; constructor(val: number) { this.val = val; this.left = null; this.right = null; } } function height(root: Node | null): number { if (!root) return 0; return 1 + Math.max(height(root.left), height(root.right)); } const root = new Node(1); root.right = new Node(2); root.right.right = new Node(3); root.right.right.right = new Node(4); console.log(height(root));
Height is the longest path from root to leaf. Here, the tree is skewed to the right.
The path is 1 -> 2 -> 3 -> 4, so height is 4.
Choose the best description of what the height of a binary tree means.
Height counts nodes, not edges or total nodes.
Height is the count of nodes on the longest path from root to leaf, including both ends.
What will be the output of the height function when the tree is empty (root is null)?
function height(root: any): number {
if (!root) return 0;
return 1 + Math.max(height(root.left), height(root.right));
}
console.log(height(null));Think about what the function returns when root is null.
The function returns 0 immediately if root is null, meaning empty tree has height 0.
Consider this height function. It causes a runtime error on some inputs. Why?
function height(root: any): number {
if (root === null) return 0;
return 1 + Math.max(height(root.left), height(root.right));
}
const root = { val: 1, left: null };
console.log(height(root));Check if all child nodes exist before accessing their properties.
root.right is undefined, so accessing root.right causes an error when height tries to recurse on it.