您的位置:首页 > 编程语言 > Python开发

LeetCode--Maximum Depth of Binary Tree (检索二叉树的最大深度)Python

2017-12-05 13:23 525 查看
题目:

给定一个二叉树,返回这个二叉树的最大深度

解题思路:

使用递归,保存所有叶子节点的深度。选择这些深度中的最大值,则为该二叉树的最大深度。

代码(Python):

# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
List = []
if root==None:
return 0
def readTree(root,count):
if root.left==None and root.right==None:
count = count+1
List.append(count)
return
elif root.left==None and root.right!=None:
count = count+1
readTree(root.right,count)
elif root.left!=None and root.right==None:
count = count+1
readTree(root.left,count)
else:
readTree(root.left,count+1)
readTree(root.right,count+1)

readTree(root,0)
print List
return max(List)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐