N叉树的深度 python实现
生活随笔
收集整理的这篇文章主要介绍了
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():'''初始化一颗测试二叉树:AB C DEFG 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 rootdef maxDepth( root):""":type root: Node:rtype: int"""if not root:return 0if not root.child_list:return 1return 1 + max(maxDepth(child) for child in root.child_list)b=init()p=maxDepth(b)print('N叉树的深度: ',p)
N叉树的深度: 3
总结
以上是生活随笔为你收集整理的N叉树的深度 python实现的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: gbdt源码解读
- 下一篇: 字典的最大深度 python 实现