首页 > 其他分享 >LeetCode 222.完全二叉树的结点个数

LeetCode 222.完全二叉树的结点个数

时间:2023-03-30 18:00:48浏览次数:42  
标签:TreeNode val int 222 二叉树 节点 root LeetCode

1.题目:

给你一棵 完全二叉树 的根节点 root ,求出该树的节点个数。

完全二叉树 的定义如下:在完全二叉树中,除了最底层节点可能没填满外,其余每层节点数都达到最大值,并且最下面一层的节点都集中在该层最左边的若干位置。若最底层为第 h 层,则该层包含 1~ 2h 个节点。


示例 1:

输入:root = [1,2,3,4,5,6] 输出:6

来源:力扣(LeetCode) 链接:https://leetcode.cn/problems/count-complete-tree-nodes 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。


2.代码:

/**
 * 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 count=0;
        while(!queue.isEmpty()){
            int len=queue.size();
            for(int i=0;i<len; i++){
                TreeNode node = queue.poll();
                count++;//就是每次抛出一个元素就计数
                if(node.left!=null) queue.offer(node.left);
                if(node.right!=null) queue.offer(node.right);
            }
        }
        return count;


    }
}

标签:TreeNode,val,int,222,二叉树,节点,root,LeetCode
From: https://blog.51cto.com/u_15806469/6159994

相关文章

  • leetcode-1089-easy
    DuplicateZerosGivenafixed-lengthintegerarrayarr,duplicateeachoccurrenceofzero,shiftingtheremainingelementstotheright.Notethatelementsbe......
  • leetcode-1317-easy
    ConvertIntegertotheSumofTwoNo-ZeroIntegersNo-Zerointegerisapositiveintegerthatdoesnotcontainany0initsdecimalrepresentation.Givenani......
  • leetcode-1009-easy
    ComplementofBase10IntegerThecomplementofanintegeristheintegeryougetwhenyouflipallthe0'sto1'sandallthe1'sto0'sinitsbinaryreprese......
  • 【LeetCode】35.搜索插入位置
    题目描述  解法思路:二分查找classSolution{public:intsearchInsert(vector<int>&nums,inttarget){intleft=0,right=nums.size()-1......
  • 【LeetCode】278.第一个错误的版本
    题目描述  解法思路:二分查找注意:当第一个 isBadVersion(mid)的结果为true时,得到第一个错误的版本//TheAPIisBadVersionisdefinedforyou.//boolisBadVe......
  • 08. 二叉树
    一、二叉树的定义  二叉树(T)是一个有穷的结点集合,这个集合可以为空,若不为空,则它是由根节点和称为其左子树\(T_{L}\)和右子树\(T_{R}\)的两个不相交的二叉树组成......
  • leetcode 176
    leetcode176第二高的薪水,查第二高的人的信息1、使用ifnull(exp1,exp2)函数,limitoffset子句 selectifnull((selectdistinctsalaryfromEmployeeorderb......
  • 树:剑指 Offer 07. 重建二叉树
    题目描述:输入某二叉树的前序遍历和中序遍历的结果,请构建该二叉树并返回其根节点。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。 示例1: Input:pre......
  • LeetCode 101.对称二叉树
    1.题目:给你一个二叉树的根节点 root ,检查它是否轴对称。 示例1:输入:root=[1,2,2,3,4,4,3]输出:true2.代码:方法一:递归实现/***Definitionforabinarytreenode.......
  • #yyds干货盘点# LeetCode程序员面试金典:盛最多水的容器
    题目:给定一个长度为n的整数数组 height 。有 n 条垂线,第i条线的两个端点是 (i,0) 和 (i,height[i]) 。找出其中的两条线,使得它们与 x 轴共同构成的容器可以......