LeetCode Maximum Depth of Binary Tree

所属专题架构实践
核心标签LeetCode
代码 / 阅读5 min
累计阅读实时统计
TL;DR · 核心摘要

Problem Given a binary tree, find its maximum depth. The maximum depth is the number of nodes along the longest path from the root node...

Problem

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.

求二叉树的最大深度

Java 实现

Java· 48 行

package com.coderli.leetcode.algorithms.easy;

/**
 * Given a binary tree, find its maximum depth.
 * <p>
 * The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
 *
 * @author OneCoder 2017-11-14 23:20
 */
public class MaximumDepthOfBinaryTree {

    public static void main(String[] args) {
        MaximumDepthOfBinaryTree maximumDepthOfBinaryTree = new MaximumDepthOfBinaryTree();
        TreeNode tree = maximumDepthOfBinaryTree.new TreeNode(1);
        TreeNode subNodeLeft = maximumDepthOfBinaryTree.new TreeNode(2);
        TreeNode subNodeRight = maximumDepthOfBinaryTree.new TreeNode(2);
        subNodeLeft.left = maximumDepthOfBinaryTree.new TreeNode(3);
        subNodeLeft.right = maximumDepthOfBinaryTree.new TreeNode(4);
        subNodeRight.left = maximumDepthOfBinaryTree.new TreeNode(4);
        subNodeRight.right = maximumDepthOfBinaryTree.new TreeNode(3);
        tree.left = subNodeLeft;
        tree.right = subNodeRight;
        System.out.println(maximumDepthOfBinaryTree.maxDepth(tree));
    }


    public int maxDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int maxLeft = maxDepth(root.left);
        int maxRight = maxDepth(root.right);
        int maxChild = maxLeft >= maxRight ? maxLeft : maxRight;
        return maxChild + 1;
    }

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }
}

分析

很容易想到递归。得到子树的最大深度,然后+1即可。本质应该也属于动态规划问题。

OneCoder 信奥远征平台 · oi.coderli.com

看完题解,马上用 240 关实战检验掌握度

覆盖 GESP 1~8 级考纲心法、CSP-J 双栏阅读程序、错题动态变式推演与 90/120 分钟全真模考。

立即闯关
开源代码与考纲字典

配套题解代码归档于 yummy-code 仓库,完整知识点索引见 GESP Wiki。

技术交流与考级答疑

欢迎加入 C++ GESP/CSP 群(688906745) 或 Java/Python 群(982860385)。

同专栏相关推荐

OneCoder

OneCoder

始于 2012

持续记录 C++ GESP/CSP 信奥算法、Java 服务端架构与 Python 工程实战。官方唯一域名:coderli.com

读者讨论与留言

共 0 条讨论
邮箱仅用于接收回复通知,不对外展示
还没有读者留言,欢迎写下你的第一条交流笔记。