111. Minimum Depth of Binary Tree

Analysis:
Can not take min of left and right, it is possible one of them is null.
Solution:


 /**  
  * Definition for a binary tree node.  
  * public class TreeNode {  
  *   int val;  
  *   TreeNode left;  
  *   TreeNode right;  
  *   TreeNode(int x) { val = x; }  
  * }  
  */  
 class Solution {  
   public int minDepth(TreeNode root) {  
     if (root == null) return 0;  
     if (root.right == null && root.left != null) return minDepth(root.left) + 1;  
     if (root.left == null && root.right != null) return minDepth(root.right) + 1;  
     return Math.min(minDepth(root.left), minDepth(root.right)) + 1;  
   }  
 }  

评论

此博客中的热门博文

776. Split BST

663. Equal Tree Partition

532. K-diff Pairs in an Array