python中二叉树的最大深度 [英] Maximum depth of a binary tree in python
问题描述
我从二叉树创建了一个元组,它看起来像这样:
I created a tuple from a binary tree and it looks like this:
元组=(1,(2,(4,5,6),(7,无,8)),(3,9,(10,11,12)))
tuple = (1,(2,(4,5,6),(7,None,8)),(3,9,(10,11,12)))
通过应用缩进,树形结构变得更加清晰:
The tree structure becomes more clear by applying indentation:
(1,
(2,
(4,
5,
6
),
(7,
None,
8
)
),
(3,
9,
(10,
11,
12
)
)
)
我知道如何使用递归方法找到二叉树的最大深度,但是我试图使用我创建的元组来找到最大深度.谁能帮助我该怎么做?
I know how to find the maximum depth of the binary tree using recursive method, but I am trying to find the maximum depth using the tuple I created. Can anyone help me with how to do it?
推荐答案
递归方法:
a = (1,(2,(4,5,6),(7,None,8)),(3,9,(10,11,12)));
def depth(x):
if(isinstance(x, int) or x == None):
return 1;
else:
dL = depth(x[1]);
dR = depth(x[2]);
return max(dL, dR) + 1;
print(depth(a));
这个想法是通过查看树的左右子树来确定树的深度.如果节点没有子树,则返回深度1.否则返回max(右侧深度,左侧深度)+ 1
The idea is to determine the depth of a tree by looking at its left and right subtree. If the node does not have subtrees, a depth of 1 is returned. Else it returns max(depth of right, depth of left) + 1
这篇关于python中二叉树的最大深度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!