测评会员优惠活动进行中 · 开通 VIP,有效期内测评不限次 VIP 优惠中 · 测评不限次 立即查看

A22254. 以下代码能够正确统计二叉树中叶⼦结点的数量。( )class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def count_leaf(root): if not root: return 0 if not root.l…

判断题 困难

题目描述

以下代码能够正确统计二叉树中叶⼦结点的数量。(    )

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

def count_leaf(root):
    if not root:
        return 0
    if not root.left and not root.right:
        return 1
    return count_leaf(root.left) + count_leaf(root.right)

if __name__ == "__main__":
    root1 = TreeNode(1)
    root1.left = TreeNode(2)
    root1.right = TreeNode(3)
    root1.left.left = TreeNode(4)
    root1.left.right = TreeNode(5)
    root1.right.right = TreeNode(6)
    print(f"二叉树1的叶子节点数: {count_leaf(root1)}")
    root2 = TreeNode(1)
    print(f"二叉树2的叶子节点数: {count_leaf(root2)}") 1
    
    root3 = None
    print(f"空树的叶子节点数: {count_leaf(root3)}")

选项(单选)

上一题 下一题