zoukankan      html  css  js  c++  java
  • 每天1题算法题(3)-二叉树的最大深度 (√)

    给定一个二叉树,找出其最大深度。

    二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。

    说明: 叶子节点是指没有子节点的节点。

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

    3
    /
    9 20
    /
    15 7
    返回它的最大深度 3 。

    简答

    1.dfs递归实现

    class Solution {
        public int maxDepth(TreeNode root) {
            if(root == null) {
                return 0;
            }
            Map<String,Integer> maxDepth = new HashMap();
            dfs(root, 1, maxDepth);
            return maxDepth.get("max") -1;
        }
    
        public void dfs(TreeNode treeNode, int currentDeep, Map<String,Integer> maxDepth) {
            if(treeNode == null) {
                Integer max = maxDepth.get("max");
                if(max == null || max < currentDeep) {
                    maxDepth.put("max", currentDeep);
                }
                return;
            }
                dfs(treeNode.left, currentDeep + 1, maxDepth);
                dfs(treeNode.right, currentDeep + 1, maxDepth);
        }
    }

      

  • 相关阅读:
    观察者模式
    php中compact,extract,list函数的使用
    加密解密
    python 线程池proxypool
    python qq音乐下载
    python 网易云音乐
    python 知识点
    python 格式化 header
    python 爬取百度图片
    php 过滤掉多维数组空值
  • 原文地址:https://www.cnblogs.com/s648667069/p/13687358.html
Copyright © 2011-2022 走看看