7.17 第一次做,无法 AC
7.18 一次 AC,但思路有点错了,明天再做一下。
7.19 一次 AC

题目描述

原题链接:https://leetcode-cn.com/problems/er-cha-shu-de-shen-du-lcof/

解题思路:后序遍历 当前根节点深度等于左右子树最大深度 + 1


K 神题解:https://leetcode-cn.com/problems/er-cha-shu-de-shen-du-lcof/solution/

  1. class Solution {
  2. public int maxDepth(TreeNode root) {
  3. if(root == null) return 0;
  4. // 后序遍历
  5. int l = maxDepth(root.left);
  6. int r = maxDepth(root.right);
  7. // 获取到当前节点的深度
  8. // 叶子节点的左右子节点都为 null,返回给叶子节点的 l 和 r 都是0,所以叶子节点的深度是1
  9. int res = Math.max(l, r) + 1;
  10. // 向上返回当前节点的深度
  11. return res;
  12. }
  13. }