一、获取二叉树的深度
就是二叉树最后的层次,如下图:

实现代码:
 代码如下:
def getheight(self):
        ''' 获取二叉树深度 '''
        return self.__get_tree_height(self.root)
    def __get_tree_height(self, root):
        if root is 0:
            return 0
        if root.left is 0 and root.right is 0:
            return 1
        else:
            left = self.__get_tree_height(root.left)
            right = self.__get_tree_height(root.right)
            if left < right:
                return right + 1
            else:
                return left + 1
二、叶子的统计
叶子就是二叉树的节点的 left 指针和 right 指针分别指向空的节点
 代码如下:
def getleafcount(self):
        ''' 获取二叉树叶子数 '''
        return self.__count_leaf_node(self.root)
    def __count_leaf_node(self, root):
        res = 0
        if root is 0:
            return res
        if root.left is 0 and root.right is 0:
            res += 1
            return res
        if root.left is not 0:
            res += self.__count_leaf_node(root.left)
        if root.right is not 0:
            res += self.__count_leaf_node(root.right)
        return res
三、统计叶子的分支节点
与叶子节点相对的其他节点 left 和 right 的指针指向其他节点
 代码如下:
def getbranchcount(self):
        ''' 获取二叉树分支节点数 '''            
新闻热点
疑难解答