【LeetCode】 104. Maximum Depth of Binary Tree 二叉树的最大深度(Easy)(JAVA)

【LeetCode】 104. Maximum Depth of Binary Tree 二叉树的最大深度(Easy)(JAVA)

题目地址: https://leetcode.com/problems/maximum-depth-of-binary-tree/

题目描述:

Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

Note: A leaf is a node with no children.

Example:

Given binary tree [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

return its depth = 3.

题目大意

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

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

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

解题方法

比较简单,直接采用递归,左右子树哪个更深即可

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int maxDepth(TreeNode root) {
        if (root == null) return 0;
        return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
    }
}

执行用时 : 0 ms, 在所有 Java 提交中击败了 100.00% 的用户
内存消耗 : 39.8 MB, 在所有 Java 提交中击败了 5.75% 的用户

猜你喜欢

转载自blog.csdn.net/qq_16927853/article/details/105799802