现在的位置: 首页 > 综合 > 正文

Minimum Depth of Binary Tree

2013年04月12日 ⁄ 综合 ⁄ 共 684字 ⁄ 字号 评论关闭

Given a binary tree, find its minimum depth.

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int minDepth(TreeNode root) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
           if(root==null){
	    	   return 0;
	       }
	       else if(root.left==null&&root.right==null){
	           return 1;
	       }
	       else if(root.left==null&&root.right!=null){
	           return 1+minDepth(root.right);
	       }
	       else if(root.left!=null&&root.right==null){
	           return 1+minDepth(root.left);
	       }
	       else {
	           return minDepth(root.left)>minDepth(root.right)?1+minDepth(root.right):1+minDepth(root.left);
	       }
    }
    
    
}

抱歉!评论已关闭.