#52 · Trees · Beginner · 45 XP · about 8 min
The depth of a binary tree is the number of nodes on the longest path from the root down to a leaf, a node with no children. Write max_depth(root) that returns the depth of the tree that starts at root. An empty tree (root is None) has depth 0.
Each node is a Node with a value val and two children, left and right, which are None when missing. The provided build makes a tree from a list of values in level order, where None marks a missing child.
4 / \ 1 7 / \ 5 9
max_depth(build([4, 1, 7, None, None, 5, 9])) # returns 3 max_depth(build([6, None, 9])) # returns 2 max_depth(build([])) # returns 0
The drawing shows the first tree. Its longest paths, 4, 7, 5 and 4, 7, 9, each have three nodes.
Ready?
Accept the challenge to start writing. A small timer counts the time this page is in view.
Output appears here.