LeetCode-Minimum Depth of Binary Tree

34 篇文章 0 订阅
作者:disappearedgod
时间:2014-6-7


题目

Minimum Depth of Binary Tree

  Total Accepted: 14139  Total Submissions: 48728 My Submissions

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.


方法


递归方法
public class Solution {
    public int minDepth(TreeNode root) {
        int depth = 0;
        if(root == null)
            return depth;
        return minDepth(root,depth);
    }
    public int minDepth(TreeNode root, int depth){
       if(root == null)
            return depth;
        int left = minDepth(root.left,depth+1);
        int right = minDepth(root.right,depth+1);
        if(root.left!=null && root.right!=null)
            return left>right?right:left;
        else if(root.left == null)
            return right;
        else 
            return left;
    }
    
}


// 2014/8/29
public class Solution {
    public int maxDepth(TreeNode root) {
        return maxDepth(root, 0);
        
    }
    public int maxDepth(TreeNode root, int depth){
        if(root == null)
            return 0;
        int left = maxDepth(root.left, depth) + 1;
        int right = maxDepth(root.right, depth) + 1;
        return left > right ? left : right;
    }
}




看了一下其他人的,不一定要用一个新的函数来传递值,其实用本身的函数迭代就可以了。
public class Solution {
    public int minDepth(TreeNode root) {
        int depth = 0;
        if(root == null)
            return depth;
        int left = minDepth(root.left) + 1;
        int right = minDepth(root.right) + 1;
        if(root.left == null)
            return right;
        if(root.right == null)
            return left;
        return right > left ? left : right;
    }
}

后面查了网上的一些其他人的blog,分享一篇blog
From:http://blog.csdn.net/du5l5ljason/article/details/8806879
---------------------------------------------------------------------------------------------分割线------------------------------- --------------------------------------------------------------

LeetCode上的题目每一道后面都有一个统计,即No. of Accepted Submission/ No. of Submission. 这可以作为一个衡量题目难易程度的标准。基本上,对于这些题目,考虑到通常interview过程,一般这样的问题会要求在30-40分钟之内解决。我也力求在设置一个timer的情况下来做题。

前10分钟,读题,思考需要问的问题,然后分析题目的思路,通常考虑一个brute force的方法,然后分析这个问题的最差解法的复杂度。然后给出一个认为的更好的解法,然后考虑复杂度。考虑要用到的数据结构,是否用到什么STL之类的library。给出算法,可以是伪码,可以是文字叙述。

10-25, or 10-35, 写代码,我通常用C/C++写。注意exception,注意函数的输入,输出,等等。

剩下5分钟,考虑test case,review code。

-----------------------------------------------------------------------------

1. Minimum Depth Of Binary Tree

Problem 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.


Step I: Interview中,面试官可能不会给出后半句的解释,因此,多问问题是一个很好的习惯。

Q1: Is binary tree complete? Is binary tree a binary search tree? Do I need to define binary tree myself? Can it have parent node?...

Q2: What is minimum depth? 这个还是很重要的。因为根据wiki (https://en.wikipedia.org/wiki/Tree_(data_structure))里的说明,The depth of a node is the length of the path to its root (i.e., its root path). 这样的话,只有一个node的树的depth是0. 而这里很显然,这样的树depth是1. What is leaf node? leaf node has no children.


Step II: 考虑解法。穷举的解法,遍历每一条path,计算path的nodes数,如果当前path的nodes数小于当前的最小值,那么替换最小值。这样是一定可以解决问题。


复杂度:假设有n个node,最多有(n+1)/2 leaf nodes,这样,相应的就有n+1/2条paths,计算每条path的长度需要O(logn), 找到这些长度中的最小值,需要O( (n+1)/2 logn ) = O(nlogn)。

递归的解法:因为根节点是一定在这条path里的,因此,这个问题可以看成是有一个重复的问题,从根节点出发,选择向左,或者向右走这两条路里面较短的一支。假设选择向左走,那么问题就转化成求以root->left为根节点的最短path的问题。这个递归的解法可以归纳为:

1. Simply case: if root == NULL, return 0; if root has no children, return 1;

2. if root has only right child, return 1 + minDepth( root->right );

    if root has only left child, return 1 + minDepth( root->left );

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

复杂度:leaf node 的 minDepth复杂度为O(1), 因为minDepth要调用n次,复杂度为O(n). 另外,由于recursion,需要O(logn)的空间

 

非递归的解法:我们将问题换一种方法陈述,求minimum depth其实就是找到那个depth最小的leaf node,也就是找到height最大的leaf node。按height遍历tree,我想到BFS。

每一次check 当前node是不是没有children,如果没有children的话,那么返回它的depth值, BFS的思路很清晰,但是假如我们发现当前search到的这个元素没有children,我们怎么返回它的depth值?

在BFS的while()循环体里面,我们找当前node是否有children,如果有,那么就将children push到队列中。每一次,push的时候,都是将该node的child nodes push进去,因此,我们可以设计一个structure,

Node {TreeNode *root; int depth;}; 

这样,每一次push的时候,都是push一个类似于Node( root->left, depth+1 )的结点,这样我们就可以记录当前node的depth了。

1. 将所有node设成unvisited, depth = 1;

2.  queue <-- (root, depth );

3. while( !queue.empty() ) u =  queue.front(), 

if u has no children, return u.depth

else

for each child  v of u

if( v is unvisited )

push (v, depth + 1 );

end

set u as visited.

复杂度: 所有leaf nodes的最小depth <= log(n), 因此复杂度为O(logn)


代码: Recursive O(n) solution:

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

代码: Iterative O(logn) solution (BFS ):
class Solution {
public:
struct Node{
    TreeNode *root;
    int depth;
    Node( TreeNode* node, int d):depth(d){
        root = node;
    }
};
    int minDepth(TreeNode *root) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if(root == NULL ) return 0;
        queue<Node> q;
        int depth = 1;
        q.push( Node( root, depth ) );
        
        while ( !q.empty() )
        {
            Node u = q.front();
            q.pop();
            if( u.root->left  ) 
                q.push( Node( u.root->left, u.depth + 1 ) );
            if( u.root->right )
                q.push( Node( u.root->right, u.depth + 1) );
            if( (!u.root->right) &&(!u.root->left) )
                return u.depth;
        }
    }
};







  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值