题目链接:https://leetcode-cn.com/problems/er-cha-shu-de-shen-du-lcof/
难度:简单

描述:
输入一棵二叉树的根节点,求该树的深度。从根节点到叶节点依次经过的节点(含根、叶节点)形成树的一条路径,最长路径的长度为树的深度。

题解

  1. # Definition for a binary tree node.
  2. # class TreeNode:
  3. # def __init__(self, x):
  4. # self.val = x
  5. # self.left = None
  6. # self.right = None
  7. class Solution:
  8. def maxDepth(self, root: TreeNode) -> int:
  9. def recursion(root, depth):
  10. if root is None:
  11. return depth-1
  12. return max(recursion(root.left, depth+1), recursion(root.right, depth+1))
  13. return recursion(root, 1)