Skip to content

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

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

Open
swiftwind0405 opened this issue Nov 4, 2020 · 0 comments
Open

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

swiftwind0405 opened this issue Nov 4, 2020 · 0 comments

Comments

@swiftwind0405
Copy link
Owner

swiftwind0405 commented Nov 4, 2020

方法一:递归

解题思想:

二叉树的最大深度即为左子树的深度与右子树深度的较大值 + 1,而求子树的深度一样可以用这个方法计算。
一直递归到空节点结束。

代码:

var maxDepth = function(root) {
    if (!root) return 0;
    if (root.left === null && root.right === null) {
        return 1;
    }
    const leftDepth = maxDepth(root.left) + 1;
    const rightDepth = maxDepth(root.right) + 1;
    return Math.max(leftDepth, rightDepth);
};

复杂度分析:

  • 时间复杂度:O(n):n取决于二叉树的节点数量,因为每个节点都只遍历一次。
  • 空间复杂度:O(height):height为二叉树的高度,递归函数需要栈空间,而栈空间取决于递归的深度,因此空间复杂度等价于二叉树的高度。

方法二:广度优先搜索

TODO

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant