Count the number of leaf nodes at the last level in a binary tree: level-order traversal

Calculate the number of leaf nodes farthest from the root node in the binary tree, that is, the number of leaf nodes at the last level in the binary tree.

For example, in the binary tree below, the total number of leaf nodes is 4 (divided into 3, 4, 6, and 8), and the number of leaf nodes at the last level is 1 (numbered 8):

     1
   /   \
  2     3
 / \
4   5
   / \
  6   7
       \
        8

Method: Level-order traversal

code:

from collections import deque


class Node:
    def __init__(self, value, left=None, right=None):
        self.value = value
        self.left = left
        self.right = right


# 计算二叉树中最后一层的叶子节点的个数
def leafNodeNum(root):
    if not root:
        return 0
    num = 0
    stack = deque()
    stack.append(root)

    # 层序遍历
    while stack:
        # 当前层级的叶子节点个数
        cur_num = 0

        length = len(stack)
        for _ in range(length):
            # 必须使用 popleft() 保证先进先出,不能使用 pop()
            # 使用 length 保证将上一层的节点全部弹出,而不弹出当前层级新加入的节点
            cur_node = stack.popleft()

            # 判断当前节点是否为叶子节点
            if not cur_node.left and not cur_node.right:
                cur_num += 1
            if cur_node.left:
                stack.append(cur_node.left)
            if cur_node.right:
                stack.append(cur_node.right)

        # 更新最大叶子节点个数
        num = max(num, cur_num)
    return num


if __name__ == '__main__':
    # 构建二叉树
    root = Node(1)
    root.left = Node(2)
    root.right = Node(3)
    root.left.left = Node(4)
    root.left.right = Node(5)
    root.left.right.left = Node(6)
    root.left.right.right = Node(7)
    root.left.right.right.left = Node(8)

    # 计算二叉树距离根节点最远的叶子节点个数
    max_leaves_count = leafNodeNum(root)
    print("二叉树中最后一层的叶子节点的数量为:", max_leaves_count)

Guess you like

Origin blog.csdn.net/qq_43799400/article/details/133187843