3
头图

The number of nodes in a complete binary tree

Topic description: Given the root node root of a complete binary tree, find the number of nodes in the tree.

The definition of a complete binary tree is as follows: In a complete binary tree, except that the bottom node may not be filled, the number of nodes in each layer reaches the maximum value, and the nodes of the bottom layer are concentrated in the leftmost position of the layer. If the bottom layer is the hth layer, the layer contains 1~ $2^{h}$ nodes.

For example descriptions, please refer to the official website of LeetCode.

Source: LeetCode
Link: https://leetcode-cn.com/problems/count-complete-tree-nodes/
The copyright belongs to Lingkou Network. For commercial reprints, please contact the official authorization, and for non-commercial reprints, please indicate the source.

Solution 1: Level-order traversal of binary tree

For binary tree level-order traversal, the binary tree is traversed in the order from top to bottom and left to right, which utilizes the characteristics of the first-in, first-out queue. The specific processing process is as follows:

  • First, if the root node is empty, it is an empty tree, indicating that there is no node, and directly returns 0;
  • Otherwise, add the root node to the queue first, then traverse the nodes in the queue until the queue is empty, recording the number of nodes during the traversal process.

Finally returns the number of nodes.

 import com.kaesar.leetcode.TreeNode;

import java.util.LinkedList;
import java.util.Queue;

public class LeetCode_222 {
    /**
     * 二叉树层序遍历
     *
     * @param root
     * @return
     */
    public static int countNodes(TreeNode root) {
        // 如果根节点为空,即为空树,说明没有节点,直接返回0
        if (root == null) {
            return 0;
        }
        // 利用队列先进先出的特性,对二叉树进行层序遍历
        Queue<TreeNode> nodes = new LinkedList<>();
        // 首先将根节点添加到队列中,作为第一层
        nodes.add(root);
        // 记录二叉树的节点数
        int count = 0;
        // 遍历队列中的节点,直到队列为空
        while (!nodes.isEmpty()) {
            count++;
            TreeNode cur = nodes.poll();
            if (cur.left != null) {
                nodes.add(cur.left);
            }
            if (cur.right != null) {
                nodes.add(cur.right);
            }
        }
        return count;
    }

    public static void main(String[] args) {
        /**
         * 测试用例:
         *       1
         *    2     3
         *   4 5   6
         */
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.right = new TreeNode(3);
        root.left.left = new TreeNode(4);
        root.left.right = new TreeNode(5);
        root.right.left = new TreeNode(6);

        // 期望输出: 6
        System.out.println(countNodes(root));
    }
}
[Daily Message] Acting as a man should be upright, like the sun and the moon.

醉舞经阁
1.8k 声望7.1k 粉丝

玉树临风,仙姿佚貌!