写在最前面:null
leetcode【104】Maximum Depth of Binary Tree
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.
Note: A leaf is a node with no children.
Example:
Given binary tree [3,9,20,null,null,15,7]
,
3 / \ 9 20 / \ 15 7
return its depth = 3
通过递归实现
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
left = Solution.maxDepth(self,root.left)
right = Solution.maxDepth(self,root.right)
if left == 0 and right != 0:
left = left + 1
if right == 0 and left != 0:
right = right + 1
return max(left, right) + 1