Maximum Depth of Binary Tree Cont…

Monisha Mathew
1 min readMay 24, 2019

--

Question: Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

You may view the full question here.

Approach 2: Let’s just tweak the previous approach a little bit to use a more efficient Data Structure — simply replace the Stack with a Queue…

//Approach 2:
//Runtime: 1ms
//Memory usage: 38MB
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int maxDepth(TreeNode root) {
Queue<TreeNode> queue = new LinkedList();
int count = 0;
if(root!=null){
count=1;
queue.add(root);
}
while(!queue.isEmpty()){
Queue<TreeNode> level = new LinkedList();
while(!queue.isEmpty()){
TreeNode curr = queue.remove();
if(curr.left!=null)
level.add(curr.left);
if(curr.right!=null)
level.add(curr.right);
}
if(!level.isEmpty()){
queue = level;
count++;
}
}
return count;
}
}

Approach 3: The previous two approaches, actually maps the entire tree. We, really don’t need that. All we need is an estimate of the length of the longest branch on the tree. Here is a brilliant solution suggested on the discussion forum using recursion. The code is crisp and concise. (No use copy-pasting it here!)

Find more posts here.

Cheers & Chao!

--

--