您的位置:首页 > 其它

Minimum Depth of Binary Tree——LeetCode(Easy)

2014-11-10 00:07 477 查看
题目:Minimum Depth of Binary Tree

要求: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
 * 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;
        }
        
        if (root->left == NULL && root->right == NULL)
        {
            return 1;
        }
        
        int minLeft = minDepth(root->left);
        int minRight = minDepth(root->right);
        
        if (minLeft == 0)
            return minRight+1;
        if (minRight == 0)
            return minLeft+1;
        
        return minLeft < minRight ? minLeft+1 : minRight+1; 
    }
};


觉得自己写的有点啰嗦,判定那一段写的不够精炼,在网上找了别人的代码比较一下:

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


看来代码这东西还是得多敲!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: