第17天|111.二叉树的最小深度 ,222.完全二叉树的节点个数

文章介绍了如何使用递归和广度优先搜索算法解决LeetCode中的两个问题:求二叉树的最小深度和计算完全二叉树的节点个数。前者通过递归计算从根到叶子节点的最短路径,后者采用BFS遍历节点并计数。
摘要由CSDN通过智能技术生成

111.二叉树的最小深度

leetcode:. - 力扣(LeetCode)

给定一个二叉树,找出其最小深度。最小深度是从根节点到最近叶子节点的最短路径上的节点数量。叶子节点是指没有子节点的节点。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public int minDepth(TreeNode root) {
        if(root == null ){
            return 0;
        }
        if(root.left == null && root.right == null ){
            return 1;
        }

        int min_depth =  Integer.MAX_VALUE; ;

        if(root.left != null){
            min_depth = Math.min(minDepth(root.left),min_depth);
        }
         if(root.right != null){
            min_depth = Math.min(minDepth(root.right),min_depth);
        }

   return min_depth + 1;
    }
}

/*
定义了一个变量min_depth,初始值设为整型的最大值Integer.MAX_VALUE。这个变量用于记录当前节点的最小深度。

然后,通过递归调用minDepth函数来计算左右子树的最小深度。如果左子树不为空,则递归调用minDepth函数,并将返回值与min_depth进行比较,取较小值更新min_depth。同样地,如果右子树不为空,则递归调用minDepth函数,并将返回值与min_depth进行比较,取较小值更新min_depth。

最后,返回min_depth + 1,表示当前节点的最小深度。*/

222.完全二叉树的节点个数

. - 力扣(LeetCode)

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public int countNodes(TreeNode root) {
        if(root == null ){
            return 0;
        }

        Queue<TreeNode> queue =  new LinkedList<>();
        queue.offer(root);
        int result = 0;

        while(!queue.isEmpty()){
            int size = queue.size();
            while(size --> 0){
               TreeNode cur = queue.poll();
                result++;
                if (cur.left != null) queue.offer(cur.left);
                if (cur.right != null) queue.offer(cur.right);

            }
        }
          return result;
    }
}


/*
代码中使用了广度优先搜索(BFS)的思想来遍历二叉树的所有节点,并统计节点的数量。

首先,判断根节点是否为空,如果为空则直接返回0。

然后,创建一个队列(queue)用于存储待遍历的节点。将根节点加入队列中,并初始化结果变量(result)为0。

接下来,使用while循环来遍历队列中的节点。在每一轮循环中,先获取当前队列的大小(size),表示当前层级的节点数量。

然后,使用内层的while循环,将当前层级的节点逐个出队,并将结果变量result加1。同时,如果当前节点的左子节点和右子节点不为空,则将它们加入队列中。

最后,当队列为空时,表示所有节点已经遍历完毕,此时返回结果变量result即可。

这段代码的时间复杂度为O(n),其中n为二叉树的节点数量。*/

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值