[勇者闯LeetCode] 110. Balanced Binary Tree

来源:互联网 发布:数据挖掘 面试 编辑:程序博客网 时间:2024/05/16 17:56

[勇者闯LeetCode] 110. Balanced Binary Tree

Description

Given a binary tree, determine if it is height-balanced.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

Information

  • Tags: Tree | Depth-first Search
  • Difficulty: Easy

Solution

利用DFS得到每个节点的高度,若节点的两个子树不平衡,则该节点的高度设为-1,最后通过二叉树的高度是否大于等于0来决定二叉树是否平衡。

Python Code

# Definition for a binary tree node.# class TreeNode(object):#     def __init__(self, x):#         self.val = x#         self.left = None#         self.right = Noneclass Solution(object):    def isBalanced(self, root):        """        :type root: TreeNode        :rtype: bool        """        return (self.get_height(root) >= 0)    def get_height(self, root):        if root is None:            return 0        left_h, right_h = self.get_height(root.left), self.get_height(root.right)        if left_h < 0 or right_h < 0 or abs(left_h - right_h) > 1:            return -1        return max(left_h, right_h) + 1;
0 0
原创粉丝点击