Tuesday, March 17, 2015

104. Maximum Depth of Binary Tree Leetcode Java

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.
Solution:
Clearly, the maximum depth of a given root, will be 1+ bigger one of its left child tree's maximum depth and its right child tree's maximum depth.
The base case its when it hit null, then means no depth and return 0.  
 public int maxDepth(TreeNode root) {  
     if(root==null) return 0;  
     return Math.max(maxDepth(root.left),maxDepth(root.right))+1;  
   }  

Since it is a tree, so performing a level order traversal can also solve this problem. The maximum depth will be the total levels of the tree.
 public int maxDepth(TreeNode root) {  
    if(root==null) return 0;  
   LinkedList<TreeNode> q=new LinkedList<TreeNode>();   
   q.offer(root);   
   int lev=0;  
   int curL=0;   
   int lastL=1;   
   while(!q.isEmpty()){   
    TreeNode cur=q.poll();   
    lastL--;   
    if(cur.left!=null) {   
     q.offer(cur.left);   
     curL++;   
    }   
    if(cur.right!=null) {   
     q.offer(cur.right);   
     curL++;   
    }   
    if(lastL==0){   
     lev++;   
     lastL=curL;   
     curL=0;   
    }   
   }   
   return lev;   
   }  

No comments:

Post a Comment