LeetCode-111. Minimum Depth of Binary Tree

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zy2317878/article/details/79945550

Description

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.

Solution 1(C++)

class Solution {
public:
    int minDepth(TreeNode* root) {
        if(!root) return 0;
        if(!root->right && !root->left) return 1;
        else if(root->right && root->left) return min(minDepth(root->right), minDepth(root->left))+1;
        else return 1 + (root->right?minDepth(root->right):minDepth(root->left));
    }
};

Solution 2(C++)

class Solution {
public:
    int minDepth(TreeNode* root){
        if(root == NULL)
                return 0;
        if(root->left == NULL && root->right == NULL)
            return 1;
        else
        {
            int l = minDepth(root->left);
            int r = minDepth(root->right);
            if(l == 0)
                l = r;
            if(r == 0)
                r = l;
            return min(l,r) + 1;
        }
    }
};

算法分析

挺简单的,就是要考虑全面,只有根节点的左右两个子节点都存在时才需要返回min(minDepth(root->right), minDepth(root->left))+1。

程序分析

阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页