23-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.

代码实现:

 1 # Definition for a binary tree node.
 2 # class TreeNode(object):
 3 #     def __init__(self, x):
 4 #         self.val = x
 5 #         self.left = None
 6 #         self.right = None
 7 
 8 class Solution(object):
 9     def maxDepth(self, root):
10         """
11         :type root: TreeNode
12         :rtype: int
13         """
14         if not root:
15             return 0
16 
17         return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))

分析:

用递归的方法,分别深入左子树和右子树中去找,当左、右子树不存在时,抵达递归基,此时return 0.

原文地址:https://www.cnblogs.com/tbgatgb/p/11020548.html