Idiot-maker

  :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

https://oj.leetcode.com/problems/minimum-depth-of-binary-tree/

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.

解题思路:

采用广度优先,也就是层次遍历的方法。遍历当前层次时,遇到一个左子树和右子树都为null的节点,证明就是叶节点,立刻返回当前深度,一定是最小深度。

不同的是,在层次遍历的基础上,用一个size变量记录当前层有多少元素,每次新的一层开始的时候,先获得queue内元素个数,然后每poll一个元素,size--,直到size==0,证明当前层次遍历结束了,这时depth才可以++。

/**
 * Definition for binary tree
 * 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;
        }
        
        int depth = 0;
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.offer(root);
        
        while(queue.size() != 0){
            //获取当前层的所有节点数量
            int size = queue.size();
            depth++;
            //size用来计数,这里的while循环不增加时间复杂度,size == 0表示当前层次遍历结束
            while(size > 0){
                root = queue.poll();
                size--;
                //左右子节点都是null,表示遇到了第一个叶节点,也就是最浅深度的地方,立刻返回
                if(root.left == null && root.right == null){
                    return depth;
                }
                if(root.left != null){
                    queue.offer(root.left);
                }
                if(root.right != null){
                    queue.offer(root.right);
                }
            }
        }
        
        return depth;
    }
}

 上面是一个迭代的算法。

其实和求二叉树的深度一样,首先想到的应该是一个递归算法。回忆一下求二叉树深度的方法,思路是,二叉树的深度就等于左子树和右子树的深度较大的那个+1。这是一个递归的算法,递归结束的条件是,当前递归节点为null,返回当前深度0。

在这个问题上,求最小深度的递归算法理解起来稍微复杂一点,也容易写错。如果单纯写成return Math.min(leftDepth, rightDepth) + 1是会出错的。考虑下面一个简单的例子:

    1

       \

         2

最小深度为2。但是左子树深度为0,右子树深度为1,min的时候显然return min(0,1) + 1 == 1了,会出错。

这里我们可以看到,对于一侧子树为空(即深度为0)的根节点,不能单纯用min()的方法,取较小的那个值了,而是直接去取另一个值。

代码如下。

/**
 * Definition for binary tree
 * 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 & root.right == null){
        //     return 1;
        // }
        
        int leftDepth = minDepth(root.left);
        int rightDepth = minDepth(root.right);
        
        if(leftDepth == 0){
            return rightDepth + 1;
        }
        
        if(rightDepth == 0){
            return leftDepth + 1;
        }
        
        return Math.min(leftDepth, rightDepth) + 1;
    }
}

 

posted on 2015-02-24 15:57  NickyYe  阅读(296)  评论(0编辑  收藏  举报