【DFS】LeetCode 104. 二叉树的最大深度

题目链接

104. 二叉树的最大深度

思路

递归求左右子树的最大深度并取最大值,返回值在最大值上+1。

递归终止条件为 root == null,此时返回 0。

代码

class Solution {
    public int maxDepth(TreeNode root) {
        if(root == null){
            return 0;
        }

        return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
    }
}
posted @ 2023-02-03 14:33  Frodo1124  阅读(16)  评论(0编辑  收藏  举报