www

导航

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

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;
    }

}

 

posted on 2020-09-21 16:23  www_practice  阅读(160)  评论(0编辑  收藏  举报