Skip to content

Problem 7: Is Binary Tree (100pts)

Problem

In computer science, a binary tree is a tree data structure in which each node has at most two children, referred to as the left child and the right child.

Write a function to test whether the given tree is a binary tree or not. Return True if it is a binary tree, otherwise return False.

在计算机科学中,二叉树(binary tree)是一种树形数据结构,其中每个节点最多有两个子节点,分别称为左子节点和右子节点。

编写一个函数来测试给定的树是否为二叉树。如果是二叉树,则返回 True,否则返回 False

def is_binary(t):
    """Returns True if t is a binary tree (each node has at most two children).

    >>> is_binary(tree(1))
    True
    >>> is_binary(tree(1, [tree(2), tree(3)]))
    True
    >>> is_binary(tree(1, [tree(2), tree(3), tree(4)]))
    False
    >>> is_binary(tree(1, [tree(2), tree(4, [tree(5), tree(6)])]))
    True
    >>> is_binary(tree(1, [tree(2), tree(4, [tree(5, [tree(6), tree(7)]), tree(8), tree(9)])]))
    False
    """
    "*** YOUR CODE HERE ***"

Hints

  • 使用 all

Solutions

需要所有节点(包括自身)的 branches 不多于两个。

```python def is_binary(t): return len(branches(t)) <= 2 and all(is_binary(b) for b in branches(t)) '''