美文网首页
Check If Binary Tree Is Balanced

Check If Binary Tree Is Balanced

作者: GakkiLove | 来源:发表于2018-04-24 21:02 被阅读0次

Check if a given binary tree is balanced. A balanced binary tree is one in which the depths of every node’s left and right subtree differ by at most 1.

Examples

        5

      /    \

    3        8

  /   \        \

1      4        11

is balanced binary tree,

        5

      /

    3

  /   \

1      4

is not balanced binary tree.

class Solution(object):
  def isBalanced(self, root):
    if not root:
      return True
    return self.helper(root) != -1
  
  def helper(self,root):
    if not root:
      return 0
    left = self.helper(root.left)
    right = self.helper(root.right)
    if left == -1 or right == -1 or abs(left - right) > 1:
      return -1
    return max(left,right) + 1

相关文章

网友评论

      本文标题:Check If Binary Tree Is Balanced

      本文链接:https://www.haomeiwen.com/subject/hmrslftx.html