Binary Tree Basics Quiz
Short prompts on node anatomy, depth vs height, and leaf counting. Foundation drills before tackling traversal, BSTs, or balanced tree problems.
Question Bank
Easy
JavaScript
3 questions
binary-tree
data-structures
quiz
fundamentals
1,122 views
9
For the tree built below, identify (a) the root, (b) every leaf, (c) the height of the tree, and (d) the depth of node 5.
Examples
Example 1:
Input: tree 1 with left subtree (2 -> (4, 5)) and right subtree (3 -> (null, 6))
Output: root = 1; leaves = {4, 5, 6}; height (edges) = 2; depth(5) = 2
Explanation: Root is the topmost node. Leaves are nodes with no children. Counting in edges, the root sits at height 2 and leaves at 0. Node 5 is two edges from the root.class Node {
constructor(value, left = null, right = null) {
this.value = value;
this.left = left;
this.right = right;
}
}
const root = new Node(1,
new Node(2, new Node(4), new Node(5)),
new Node(3, null, new Node(6))
);Implement countLeaves(root) returning the number of leaf nodes in a binary tree. Recursion is fine; aim for O(n) time, O(h) space.
Examples
Example 1:
Input: tree 1 -> (2 -> (4, 5), 3)
Output: 3
Explanation: Nodes 4, 5, and 3 are leaves (both children null), nodes 1 and 2 are internal. Recursion returns 0 for null, 1 for leaves, and the sum of subtree counts otherwise.Example 2:
Input: tree = single node 7
Output: 1
Explanation: A solitary root is itself a leaf, so the count is 1.function countLeaves(root) {
// TODO: return the leaf count
}Explain the difference between depth and height in a binary tree, and state both for the root and for every leaf using one convention.
