首页 > 代码库 > Leetcode:minimum_depth_of_binary_tree题解

Leetcode:minimum_depth_of_binary_tree题解

一、     题目

  和求最深二叉树相似,给定一个二叉树,求它的最小深度。最小深度是沿从根节点,到叶节点最短的路径。

二、     分析

  当我看到这个题目时,我直接将最深二叉树的代码稍微改了下,把max改成min,本以为应该没有问题,谁知道WA了两次,我静下来看了看,终于知道了,当遇到有结点为NULL时就得要结束了。所以下次再简单的题目也要静下来好好分析,不然会容易出错。

 

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int minDepth(TreeNode *root) {
        if(root==NULL) 
        	return 0;
        int mleft=minDepth(root->left);
        int mright=minDepth(root->right);
        if(mleft==0)
           return 1+mright;
        else if(mright==0)
           return 1+mleft;   
        else return min(mleft,mright)+1;
    }
};

二、

 
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */

class Solution {
public:
    int minDepth(TreeNode *root) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        return minRec(root);
    }
    
    int minRec( TreeNode * root) {
        if(!root) return 0;
        
        int left = minRec( root->left);
        int right = minRec( root->right);
        
        if(left && right) return 1 + min(left, right);
        if(left || right) return 1+left+right;
        return 1;
    }
};
三、

 
/**
 * 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) {
        // Start typing your Java solution below
        // DO NOT write main() function

        return minRec(root);
    }
    
    private int minRec(TreeNode root) {
        if(root==null) return 0;
        
        int l = minRec(root.left);
        int r = minRec(root.right);
        
        if(l==0) return r+1;
        if(r==0) return l+1;
        
        return Math.min(l, r) + 1;
        
    }
}


Leetcode:minimum_depth_of_binary_tree题解