二叉树的最大深度(Maximum Depth of Binary Tree)java

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhangjingao/article/details/82053107

二叉树的最大深度(Maximum Depth of Binary Tree)java

题干


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

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

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

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

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

分析

这是一个明显的dfs题。我们使用递归搜索,找出当前分支长度与最大值比较,返回较大者即可。

代码


    public int maxDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        return num(root, 1,0);
    }

    private int num (TreeNode treeNode, int depth, int max) {
        if (treeNode.left == null && treeNode.right == null) {
            return depth > max ? depth : max;
        }
        if (treeNode.left != null) {
            max = num(treeNode.left, depth+1, max);
        }
        if (treeNode.right != null) {
            max = num(treeNode.right, depth+1, max);
        }
        return max;
    }

运行结果

这里写图片描述

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhangjingao/article/details/82053107

猜你喜欢

转载自blog.csdn.net/zhangjingao/article/details/82053107