sorry最近太忙,没怎么刷leetcode.
Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
题目意思很简单了,给你一颗二叉树,让你去算它深度多少。解题思路:递归遍历二叉树即可。
代码:
# 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
"""
if not root:
return 0
self.max=0
def find(root,count):
if root:
if count>self.max: self.max=count
find(root.left,count+1)
find(root.right,count+1)
find(root,0)
return self.max+1
s=Solution()
Tree=TreeNode(3)
Tree.left=TreeNode(9)
Tree.right=TreeNode(20)
Tree.right.left=TreeNode(15)
Tree.right.left.left=TreeNode(15)
print(s.maxDepth([]))
请注意当输入的树是空的时候,应返回0.
更简单的解法:
def maxDepth(self, root):
if not root:
return 0
return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))