您的位置:首页 > 其它

leetcode之Minimum Depth of Binary Tree

2016-04-11 21:36 295 查看
采用递归思想,这次是求最小深度。

(1)C语言实现

/**

 * Definition for a binary tree node.

 * struct TreeNode {

 *     int val;

 *     struct TreeNode *left;

 *     struct TreeNode *right;

 * };

 */

 int min(int x, int y){

     return x<y?x:y;

 }

int minDepth(struct TreeNode* root) {

    if(!root)

        return 0;

    if(!root->left)

        return 1+minDepth(root->right);

    if(root->right==NULL)

        return 1+minDepth(root->left);

    return 1+min(minDepth(root->left), minDepth(root->right));

}

(2)C++实现

/**

 * Definition for a binary tree node.

 * 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)

            return 0;

        if(!root->left)

            return 1+minDepth(root->right);

        if(!root->right)

            return 1+minDepth(root->left);

        return min(minDepth(root->left), minDepth(root->right))+1;

    }

};

(3)java实现

/**

 * Definition for a binary tree node.

 * public class TreeNode {

 *     int val;

 *     TreeNode left;

 *     TreeNode right;

 *     TreeNode(int x) { val = x; }

 * }

 */

public class Solution {

    public int minDepth(TreeNode root) {

        if(root == null)

            return 0;

        if(root.left == null)

            return 1+minDepth(root.right);

        if(root.right == null)

            return 1+minDepth(root.left);

        return 1+Math.min(minDepth(root.left), minDepth(root.right));

    }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: