zl程序教程

您现在的位置是:首页 >  后端

当前栏目

字典的最大深度 python 实现

Python 实现 深度 最大 字典
2023-09-14 09:09:29 时间

从本质上讲嵌套字典是一颗任意的多叉树,可以参考我的博客如何求多叉树的深度

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

@author: lg
"""
d={'a':{'b':3,
        'c':{'d':4,'e':5
            }
       },
    'f':9
    }

def maxDepth( root):
    if type(root)==int:
        return 0
    if type(root.values)==int:
        return 1
    return 1 + max(maxDepth(child) for child in root.values())
    
p=maxDepth(d)
print('字典的最大深度是: ',p)