其他分享
首页 > 其他分享> > P18-二叉树最小深度-广度优先

P18-二叉树最小深度-广度优先

作者:互联网

//二叉树的最小深度
/*
 * 给定一个二叉树,找出其最小深度
 * 最小深度是从根节点到最近叶子节点的最短路径上的节点数量
 * */
public class P18 {
    static class TreeNode{
        int val;
        TreeNode left;
        TreeNode right;

        //记录当前深度
        int deep;

        TreeNode(int val, TreeNode left, TreeNode right){
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public static void main(String[] args) {
        TreeNode node7 = new TreeNode(7, null, null);
        TreeNode node6 = new TreeNode(6, node7, null);
        TreeNode node5 = new TreeNode(5, null, null);
        TreeNode node4 = new TreeNode(4, null, null);
        TreeNode node3 = new TreeNode(3, node6, null);
        TreeNode node2 = new TreeNode(2, node4, node5);
        TreeNode node1 = new TreeNode(1, node2, node3);
        System.out.println(minDepth(node1));
    }

    //广度优先,从根节点向下计算,一层一层遍历,找到一个根节点就已经是最小深度
    //问题是如果一层一层来?遍历2的时候,怎么做到再遍历3?
    //利用queue,先1进入queue,如果不是叶子,就把左右节点都入队,
    //然后左出队,不是叶子节点,又把孩子进队,右出队.......
    public static int minDepth(TreeNode root){
        if(root == null){
            return 0;
        }

        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        root.deep = 1;
        queue.offer(root);

        //
        while(!queue.isEmpty()){
            TreeNode node = queue.poll();
            if(node.left == null && node.right == null){
                return node.deep;
            }

            if(node.left != null){
                node.left.deep = node.deep + 1;
                queue.offer(node.left);
            }

            if(node.right != null){
                node.right.deep = node.deep + 1;
                queue.offer(node.right);
            }
        }

        //不会走到这的,会再while中找到叶子节点就返回了
        return 0;
    }

}

 

标签:node,right,TreeNode,queue,二叉树,new,P18,广度,null
来源: https://www.cnblogs.com/YonchanLew/p/16129185.html