zoukankan      html  css  js  c++  java
  • 剑指 Offer 55

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

    例如:

    给定二叉树 [3,9,20,null,null,15,7]

        3
       / 
      9  20
        /  
       15   7

    返回它的最大深度 3 。

    方法一:后序遍历(DFS)
    树的后序遍历 / 深度优先搜索往往利用 递归 或 栈 实现,本文使用递归实现。
    关键点: 此树的深度和其左(右)子树的深度之间的关系。显然,此树的深度 等于 左子树的深度 与 右子树的深度 中的 最大值 +1+1 。

    class Solution {
        public int maxDepth(TreeNode root) {
            if(root == null) return 0;
            return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
        }
    }
  • 相关阅读:
    python 文件目录/方法
    python文件
    python模块
    python数据结构
    python函数
    python迭代器和生成器
    python循环语句
    python控制语句 if
    python数字
    个人课程总结
  • 原文地址:https://www.cnblogs.com/kpwong/p/14688072.html
Copyright © 2011-2022 走看看