Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

104. 二叉树的最大深度 #32

Open
pigpigever opened this issue Dec 19, 2019 · 0 comments
Open

104. 二叉树的最大深度 #32

pigpigever opened this issue Dec 19, 2019 · 0 comments
Labels
二叉树 递归 递归类型的算法题

Comments

@pigpigever
Copy link
Owner

题目剖析

给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。

解题思路

尝试把这道题讲得更加清晰明白一些。
不妨假设有一种极端的二叉树,右节点全部为空(退化成链表)

image.png

显然,如果我们要拿到这个特殊的二叉树的深度的话,可以从底部递增,最后返回这个值。

image.png

我们第一版的代码可以是这样👇

/**
 * @param {TreeNode} root
 * @return {number}
 */
var maxDepth = function(root) {
    if (!root) {
        return 0
    }
    return maxDepth(root.left) + 1
};

同样的,如果左子树全部为空,代码可以这样写👇

/**
 * @param {TreeNode} root
 * @return {number}
 */
var maxDepth = function(root) {
    if (!root) {
        return 0
    }
    return maxDepth(root.right) + 1
};

根据上面的代码,左右子树的深度我们都能拿到。在不只考虑极端情况的时候,其实我们只要比较左右子树的深度就行了。

示例代码

/**
 * @param {TreeNode} root
 * @return {number}
 */
var maxDepth = function(root) {
    if (!root) {
        return 0
    }
    return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1
};
@pigpigever pigpigever added 递归 递归类型的算法题 二叉树 and removed 二叉树 labels Dec 19, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
二叉树 递归 递归类型的算法题
Projects
None yet
Development

No branches or pull requests

1 participant