算法流程:
  • 本质上是对树作后序遍历

  • 每次递归每个节点 root 的左右子树,并且只得到左右子树中较大的子树深度。

  • 当前节点 root 左右子树递归到叶子节点后,root == null,递归开始自底向上返回,每次向上 return 都 + 1, 即深度 + 1



# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    def TreeDepth(self, pRoot):
        # write code here
# 递归终止条件:递归到叶子节点
        if pRoot == None:
            return 0
# 得到左右子树中较大的子树深度
        return max(self.TreeDepth(pRoot.left),self.TreeDepth(pRoot.right)) +1