文章

LeetCode Maximum Depth of Binary Tree

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 实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
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即可。本质应该也属于动态规划问题。

所有代码已上传至Github:https://github.com/lihongzheshuai/yummy-code

GESP 学习专题站:GESP WIKI

"luogu-"系列题目可在洛谷题库进行在线评测。

"bcqm-"系列题目可在编程启蒙题库进行在线评测。

欢迎加入Java、C++、Python技术交流QQ群(982860385),大佬免费带队,有问必答

欢迎加入C++ GESP/CSP认证学习QQ频道,考试资源总结汇总

欢迎加入C++ GESP/CSP学习交流QQ群(688906745),考试认证学员交流,互帮互助

GESP/CSP 认证学习微信公众号
GESP/CSP 认证学习微信公众号
本文由作者按照 CC BY-NC-SA 4.0 进行授权