Maximum Depth of Binary Tree
You get the root of a binary tree. Find its depth: how many nodes lie on the longest path from the root down to a leaf. Our tree: 11 with children 4 and 8; 8 has children 2 and 13; 2 has a left child 6 — the answer is 4: the path 11 → 8 → 2 → 6.
- input
root: a binary tree, written as on LeetCode: its values level by level, left to right,nullfor a missing child.- returns
- Its maximum depth: how many nodes the longest path from the root down to a leaf has; 0 for an empty tree.
- constraints
- 0 ≤ the number of nodes ≤ 1000
- −100 ≤ Node.val ≤ 100
- examples
- Open a test in the tests panel: it shows the input and the expected answer.
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
function maxDepth(root) {
}
Ctrl ↵
format
reset
saved in this browser
Stuck?
See the solution run step by step on our example, then why it works and its complexity.
Next: more depth-first search (dfs) problems
- 100Same TreeEasysolve
- 226Invert Binary TreeEasysolve
- 101Symmetric TreeEasysolve
- 112Path SumEasysolve
- 200Number of IslandsMediumsolve
- 695Max Area of IslandMediumsolve
- 133Clone GraphMediumsolve
- 417Pacific Atlantic Water FlowMediumsolve
- 129Sum Root to Leaf NumbersMediumsolve
- 222Count Complete Tree NodesMediumsolve
- 236Lowest Common Ancestor of a Binary TreeMediumsolve
- 130Surrounded RegionsMediumsolve
- 399Evaluate DivisionMediumsolve
- 124Binary Tree Maximum Path SumHardsolve
The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.