1

二叉树的深度(算法39)

 2 years ago
source link: https://allenwind.github.io/blog/2982/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
Mr.Feng Blog

NLP、深度学习、机器学习、Python、Go

二叉树的深度(算法39)

问题:输入二叉树的根结点,求该树的深度。

从根结点到叶结点依次经过的结点形成树的一条路径,最长的路径长度为树的深度(深度为该路径的结点数)。

为了找到以根结点为树的根结点的深度需要找到左右子树的深度,依次递归下去不难写出如下代码。

def tree_depth(tree):
if not tree:
return 0
left = tree_depth(tree.left)
right = tree_depth(tree.right)
if left > right:
left += 1
return left
else:
right += 1
return right

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK