python二叉树深度计算,python中二叉树的最大深度

I created a tuple from a binary tree and it looks like this:

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?

解决方案

Recursive method:

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));

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值