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

110. 平衡二叉树 #60

Open
swiftwind0405 opened this issue Jan 31, 2021 · 0 comments
Open

110. 平衡二叉树 #60

swiftwind0405 opened this issue Jan 31, 2021 · 0 comments

Comments

@swiftwind0405
Copy link
Owner

swiftwind0405 commented Jan 31, 2021

方法一:暴力法

解题思想:
自顶向下的比较每个节点的左右子树的最大高度差,如果二叉树中每个节点的左右子树最大高度差小于等于 1 ,即每个子树都平衡时,此时二叉树才是平衡二叉树

代码:

var isBalanced = function (root) {
  if(!root) return true
  return Math.abs(depth(root.left) - depth(root.right)) <= 1
        && isBalanced(root.left)
        && isBalanced(root.right)
}
var depth = function (node) {
    if(!node) return -1
    return 1 + Math.max(depth(node.left), depth(node.right))
}

复杂度分析:

  • 时间复杂度:O(nlogn),计算 depth 存在大量冗余操作
  • 空间复杂度:O(n)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant