N叉树的深度 python实现

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed May 15 17:30:11 2019

@author: lg
"""
#节点数据结构
class Node(object):
    # 初始化一个节点
    def __init__(self,value = None):
        self.value = value  # 节点值
        self.child_list = []    # 子节点列表
    # 添加一个孩子节点
    def add_child(self,node):
        self.child_list.append(node)


# 初始化一颗测试二叉树
def init():
    '''
    初始化一颗测试二叉树:
            A
        B   C   D
      EFG       HIJ
    '''
    root = Node('A')
    B = Node('B')
    root.add_child(B)
    root.add_child(Node('C'))
    D = Node('D')
    root.add_child(D)
    B.add_child(Node('E'))
    B.add_child(Node('F'))
    B.add_child(Node('G'))
    D.add_child(Node('H'))
    D.add_child(Node('I'))
    D.add_child(Node('J'))
    return root


def maxDepth( root):
    """
    :type root: Node
    :rtype: int
    """
    if not root:
        return 0
    if not root.child_list:
        return 1
    return 1 + max(maxDepth(child) for child in root.child_list)

b=init()

p=maxDepth(b)

print('N叉树的深度: ',p)
N叉树的深度:  3
posted @ 2022-08-19 22:53  luoganttcc  阅读(12)  评论(0)    收藏  举报