首页 > 其他 > 详细

p15 二叉树的最小深度 (leetcode 111)

时间:2020-03-10 17:11:11      阅读:49      评论:0      收藏:0      [点我收藏+]

一:解题思路

 方法一:递归法。

方法二:迭代法,利用二叉树的层级遍历的思想,找到与根节点最近的叶子节点,这个时候就知道二叉树的最小深度了。

二:完整代码示例 (C++版和Java版)

递归版C++:

//Time:O(n),Space:O(n)
class
Solution { public: int min(int a, int b) { return a < b ? a : b; } int minDepth(TreeNode* root) { if (root == NULL) return 0; if ((root->left == NULL) && (root->right != NULL)) return minDepth(root->right) + 1; if ((root->left != NULL) && (root->right == NULL)) return minDepth(root->left) + 1; return min(minDepth(root->left),minDepth(root->right)) + 1; } };

迭代法C++:

//Time:O(n),Space:O(n)
class Solution 
{
public:
    int minDepth(TreeNode* root) 
    {
        if (root == NULL) return 0;

        queue<TreeNode*> queue;

        queue.push(root);
        int depth = 1;

        while (!queue.empty())
        {
            int size = queue.size();

            for (int i = 0; i < size; i++)
            {
                TreeNode* t = queue.front();
                queue.pop();

                if ((t->left == NULL) && (t->right == NULL)) return depth;
                if ((t->right != NULL)) queue.push(t->right);
                if ((t->left != NULL))  queue.push(t->left);
            }

            depth++;
        }
        
        return -1;
    }
};

递归版Java:

class Solution
{
    public int minDepth(TreeNode root)
    {
          if(root==null) return 0;
          if((root.left==null)&&(root.right!=null)) return minDepth(root.right)+1;
          if((root.left!=null)&&(root.right==null)) return minDepth(root.left)+1;

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

迭代版Java:

class Solution
{
    public int minDepth(TreeNode root)
    {
        if(root==null) return 0;
        
        Queue<TreeNode> queue=new LinkedList<>();

        queue.add(root);
        int depth=1;

        while(!queue.isEmpty())
        {
            int size=queue.size();
            for(int i=0;i<size;i++)
            {
                TreeNode t=queue.poll();

                if(t.left==null&&t.right==null) return depth;
                if(t.left!=null) queue.add(t.left);
                if(t.right!=null) queue.add(t.right);
            }

            depth++;
        }

        return -1;
    }
}

 

p15 二叉树的最小深度 (leetcode 111)

原文:https://www.cnblogs.com/repinkply/p/12455723.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!