Given a binary tree, find its maximum depth. The maximum depth is defined as the number of nodes along the path from the root node to the deepest leaf node. |
The maximum height of a binary tree is defined as the number of nodes along the path from the root node to the deepest leaf node. Note that the maximum height of an empty tree is 0. Recursive Solution:
Further Thoughts: ![]() Binary-tree visualization of the Yahoo search engine bot crawling the experimental website. The total number of nodes grow with an exponential rate as the tree deepens. The animated version showing the tree growing over the year can be found here (Warning: large file size, 13MB). Hint: Iterative Solution: As pre-order and in-order iterative traversals are easier to implement, your best bet is to code either one of them during an interview session. As we traverse the tree, we would keep track of the current depth and record each node's depth, so that we know which depth we are in when we return to the node at a later time. (In pre-order or in-order traversals, it might return several levels above the current level when a node is popped off the stack). On the other hand, post-order traversal guarantees to return exactly one level above a node that is popped off the stack. Therefore, we could devise a solution utilizing post-order traversal without modifying the existing tree structure. We keep track of the current depth and update the maximum depth as we traverse the tree. Another solution is to utilize Breadth-first Search (BFS). Unlike DFS, we traverse the tree level by level, thus we are able to obtain the max depth in a direct manner. Read my post: Printing a Binary Tree in Level Order for more information. Below is the code for finding the maximum depth of a binary tree using post-order traversal, without recursion.
|
I used a Breadth-first Search method to solve this problem. Two queues implemented as LinkedLists in Java are maintained.
|
|
Breadth First Traversal with a variable control the level
|
|
use dfs travelsal, and record the node depth with the node point; when visit leaf(not must) then compare the maxdepth.
|
int maxDepth(TreeNode *root) {
}
link
This answer is marked "community wiki".
|