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

 

  

posted @ 2020-09-17 20:09  GodTelMe  阅读(125)  评论(0编辑  收藏  举报