完全二叉树的节点个数 (Count Complete Tree Nodes)

 

思路:

// @Title: 完全二叉树的节点个数 (Count Complete Tree Nodes)
// @Author: qisiii
// @Date: 2024-09-15 00:31:24
// @Runtime: 4 ms
// @Memory: 45.8 MB
// @comment: 
// @flag: 
/**
 * 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);
        Integer sum=0;
        while (!queue.isEmpty()) {
            int size = queue.size();
            sum+=size;
            while (size > 0) {
                TreeNode node = queue.poll();
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
                size--;
            }
        }
        return sum;
    }
}
Licensed under CC BY-NC-SA 4.0
最后更新于 2024-10-18