Monday, September 15, 2014

Maximum Depth of Binary Tree

Very simple, just get the max depth. But one confusing thing is that depth of root should be 0, and height of leaf should be 0. For understanding about depth and height, please check this link out:
But the AC answer shows that if there is only one root, maximum depth of this tree is 1. Need to discuss about this with my friend. 




 /**  
  * Definition for binary tree  
  * public class TreeNode {  
  *   int val;  
  *   TreeNode left;  
  *   TreeNode right;  
  *   TreeNode(int x) { val = x; }  
  * }  
  */  
 public class Solution {  
   public int maxDepth(TreeNode root) {  
     if(root == null) return 0;  
     int maxDepthVal = 0;  
     maxDepthVal = Math.max(maxDepthVal, Math.max(maxDepth(root.right),maxDepth(root.left)) + 1 );  
     return maxDepthVal;  
   }  
 }  

No comments:

Post a Comment