首页 > 其他 > 详细

广度遍历-二叉树最小深度

时间:2020-09-21 22:11:19      阅读:61      评论:0      收藏:0      [点我收藏+]
package bfs;

import java.util.LinkedList;
import java.util.Queue;

public class TreeMinDepth {

    /**
     * 定义TreeNode
     */
    private static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }

    // 二叉树最小深度
    int minDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        Queue<TreeNode> q = new LinkedList<>();
        q.offer(root);
        // root != null
        int depth = 1;
        while (q.size() > 0) {
            for (int i = 0; i < q.size(); i++) {
                TreeNode cur = q.poll();
                // 叶子节点
                if (cur.left == null && cur.right == null) {
                    return depth;
                }
                if (cur.left != null) {
                    q.offer(cur.left);
                }
                if (cur.right != null) {
                    q.offer(cur.right);
                }
            }
            depth++;
        }
        return depth;
    }

}

 

广度遍历-二叉树最小深度

原文:https://www.cnblogs.com/zhwcs/p/13706321.html

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