如何计算二叉树的叶子?

时间:2016-10-30 19:29:02

标签: python python-3.x

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

class BST:

    def __init__(self):
        self.root = None

    def recurse_add(self, ptr, item):
        if ptr == None:
            return Node(item)
        elif item < ptr.item:
            ptr.left = self.recurse_add(ptr.left, item)
        elif item > ptr.item:
            ptr.right = self.recurse_add(ptr.right, item)
        return ptr

这是我的尝试:

def count_leaves(self):
        ptr = self.root
        counter = 0
        if ptr.left is None and ptr.right is None:
            counter += 1
        if ptr.left:
            counter += self.count_leaves()
        if ptr.right:
            counter += self.count_leaves()
        return counter

我有一个RecursionError,无论如何我可以解决这个问题吗?有人可以向我解释如何计算二叉树的叶子吗?

1 个答案:

答案 0 :(得分:2)

当您计算假期时,您总是从self节点重复。

def count_leaves(self):
    ptr = self.root  # reseting at the root
    ...
    counter += self.count_leaves()  # recurses from the top of the tree

您的第二个问题似乎与添加节点的方式有关。

例如,

def recurse_add(self, ptr, item):
    if prt == None:
        # say this is false
    ptr.left = self.recurse_add(ptr.left, item)
    ...
    return ptr  # The recursive call will return 'ptr.left'

所以,ptr.left = ptr.left

的情况基本上是ptr != None

你需要迭代。我通常在Node类上实现所有递归方法,而不是传递Tree类中的指针。

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

    def is_leaf(self):
        return self.right is None and self.left is None

    def add(self, item):
        if item <= self.item:
            self.left = Node(item) if self.left is None else self.left.add(item)
        elif item > self.item:
            self.right = Node(item) if self.right is None else self.right.add(item)
        return self

    def count_leaves(self):
        counter = 0
        if self.is_leaf():
            counter += 1
        if self.left is not None:
            counter += self.left.count_leaves()
        if self.right is not None:
            counter += self.right.count_leaves()
        return counter

现在,如果您有根,只需将方法委托给树中的根。

class BST:

    def __init__(self):
        self.root = None

    def is_empty(self):
        return self.root is None

    def add(self, item):
        if self.is_empty():
            self.root = Node(item)
        else:
            self.root.add(item)

    def count_leaves(self):
        return 0 if self.is_empty() else self.root.count_leaves()