[LeetCode] 104. Maximum Depth of Binary Tree

Given the root of a binary tree, return its maximum depth.

A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

Example 1:
Example 1
Input: root = [3,9,20,null,null,15,7]
Output: 3

Example 2:
Input: root = [1,null,2]
Output: 2

Constraints:
The number of nodes in the tree is in the range [0, 104].
-100 <= Node.val <= 100

二叉树的最大深度。

给定一个二叉树 root ,返回其最大深度。
二叉树的 最大深度 是指从根节点到最远叶子节点的最长路径上的节点数。

思路

这是后序遍历的基础题,直接上代码。影子题 543。

复杂度

时间O(n)
空间O(h) - 树的高度

代码

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) {
        // corner case
        if (root == null) {
            return 0;
        }
        // normal case
        int leftMax = maxDepth(root.left);
        int rightMax = maxDepth(root.right);
        return Math.max(leftMax, rightMax) + 1;
    }
}

相关题目

104. Maximum Depth of Binary Tree
110. Balanced Binary Tree
366. Find Leaves of Binary Tree
543. Diameter of Binary Tree
1522. Diameter of N-Ary Tree
1245. Tree Diameter
posted @ 2020-01-07 02:55  CNoodle  阅读(444)  评论(0编辑  收藏  举报