LeetCode 104. Maximum Depth of Binary Tree 二叉树的最大深度

题目

https://leetcode.com/problems/maximum-depth-of-binary-tree/description/

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.

讲解

可以列出所有可能的二叉树形状,再分别总结其最大深度的特点:

  1. 当二叉树是null时,最大深度就为0
  2. 当二叉树只有根节点时,最大深度为1
  3. 当二叉树有根节点还有其他子节点时候,最大深度为左、右子树深度较大一边的深度加上1

视频教学

Java参考代码

/**
 * 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;
        }
        
        int leftDepth = maxDepth(root.left);
        int rightDepth = maxDepth(root.right);
        
        return Math.max(leftDepth, rightDepth) + 1;
    }
}

发表评论

电子邮件地址不会被公开。 必填项已用*标注