美文网首页
LeetCode 111.二叉树的最小深度

LeetCode 111.二叉树的最小深度

作者: 饼干不干 | 来源:发表于2019-05-23 23:08 被阅读0次

给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7
返回它的最小深度  2.

C

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
int minDepth(struct TreeNode* root){
    if(root==NULL)
        return 0;
    else if(root->left == NULL&&root->right == NULL)
        return 1;
    else if(root->left == NULL && root->right != NULL)
        return minDepth(root->right) + 1;
    else if(root->right == NULL && root->left != NULL)
        return minDepth(root->left) + 1;
    else if(root->right != NULL && root->left != NULL){
        int leftdepth = minDepth(root->left);
        int rightdepth = minDepth(root->right);
        if(leftdepth<rightdepth)
            return leftdepth+1;
        else 
            return rightdepth+1;
    }
    return 0;
}    

相关文章

网友评论

      本文标题:LeetCode 111.二叉树的最小深度

      本文链接:https://www.haomeiwen.com/subject/zsgizqtx.html