判断题 偏易
#16964

以下代码能够正确统计二叉树中叶子结点的数量。 class TreeNode : def __init__ ( self , val = 0 , left = N…

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

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)}")


未登录也能判分,登录后才会记录
答案与解析
正确答案:对
解析
分析二叉树结构,识别叶子结点的定义为左右子树均为空的结点。通过递归遍历根结点,判断当前结点是否为空,若为空则返回0;若当前结点为叶子结点则返回1;否则递归计算左子树和右子树的叶子结点数量并求和。对每个测试用例,分别构建对应的二叉树或空树,调用统计函数处理不同形态的树结构,包括单结点树、多层树及空树的情况。