Maximum Depth of Binary Tree
EasyNeetCode 150Top Interview 150 TreesYahooArista NetworksProblem
Given the root of a binary tree, return how many levels it has: the number of nodes on the
longest path that starts at the root and goes down to a leaf.
An empty tree has depth 0. The tree is given in level order, with null for a missing child.
Constraints
- 0 ≤ number of nodes ≤ 10000
- -100 ≤ Node.val ≤ 100
Examples: pick one to animate
Solutions
TimeO(n)
SpaceO(h)
Time: Every node is visited exactly once.
Space: The recursion goes as deep as the tree is tall, h. That is log n for a balanced tree and n for a chain.
The depth of a node is 1 plus the larger depth of its two children. An empty node has depth 0, which is the base case. Ask both children, take the bigger answer and add one.