题目:
给定一个二叉树,返回这个二叉树的最大深度
解题思路:
使用递归,保存所有叶子节点的深度。选择这些深度中的最大值,则为该二叉树的最大深度。
代码(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)