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);
        }
    }

      

  • 相关阅读:
    LaTeX插入数学公式
    清除浮动的4种方式
    水平居中与垂直居中
    如何实现两三栏布局
    BFC
    flex弹性盒子
    盒模型
    Git
    jQuery设置disabled属性与移除disabled属性
    TP---where多条件查询
  • 原文地址:https://www.cnblogs.com/s648667069/p/13687358.html
Copyright © 2011-2022 走看看