美文网首页
P17-二叉树最小深度-深度优先

P17-二叉树最小深度-深度优先

作者: YonchanLew | 来源:发表于2021-05-14 16:16 被阅读0次
    //二叉树的最小深度
    /*
     * 给定一个二叉树,找出其最小深度
     * 最小深度是从根节点到最近叶子节点的最短路径上的节点数量
     * */
    public class P17 {
        static class TreeNode{
            int val;
            TreeNode left;
            TreeNode right;
    
            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));
        }
    
        //深度优先
        public static int minDepth(TreeNode root){
            if(root == null){
                return 0;
            }
    
            //叶子节点,深度为1,是我们定义的
            if(root.left == null && root.right == null){
                return 1;
            }
    
            int min = Integer.MAX_VALUE;
    
            if(root.left != null){
                min = Math.min(minDepth(root.left), min);
            }
            if(root.right != null){
                min = Math.min(minDepth(root.right), min);
            }
    
            //左右深度+自己
            return min + 1;
        }
        
    }
    

    相关文章

      网友评论

          本文标题:P17-二叉树最小深度-深度优先

          本文链接:https://www.haomeiwen.com/subject/xkyndltx.html