算法题——Minimum Depth of Binary Tree(JAVA)

题目描述:
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.

读题:
找出二叉树的最短深度。用广度优先搜索。

知识储备:
广度优先搜索树
1. 从根节点开始,搜索他的子节点;
2. 搜索所有处在第二层子节点他们的子节点;
3. 以此类推;
4. 直到某个节点不存在子节点,则该节点到根节点的路径为最短路径。

Queue队列:
主要用到的函数

add增加一个元素如果队列已满,则抛出一个IIIegaISlabEepeplian异常
remove 移除并返回队列头部的元素如果队列为空,则抛出一个NoSuchElementException异常
peek返回队列头部的元素如果队列为空,则返回null
size返回队列的大小如果队列为空,则返回0



解题思路:
1. 用队列来存储每一层的节点;
2. 从根节点开始,把每一层的节点放入队列,记录队列大小,即该层的节点数;
2. 当循环次数小于该层节点数,从队列的头部开始,如果该节点有子节点,则将他的子节点放进队列尾部,然后移除该节点;
3. 以此类推;
4. 直到某个节点不存在子节点,则结束。

提交代码:

/**
 * Definition for a binary tree node.
 * 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;
        }
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        int depth = 1;
        queue.add(root);
        TreeNode head = root;
        while (true) {
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                if (head.left == null && head.right == null) {
                    return depth;
                } else {

                    if (head.left != null) {
                        queue.add(head.left);
                    }
                    if (head.right != null) {
                        queue.add(head.right);
                    }
                    queue.remove();
                    head = queue.peek();
                }
            }
            depth++;

        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值