首页 > 编程语言 > 详细

[LeetCode]题解(python):110 Balanced Binary Tree

时间:2016-05-17 17:30:18      阅读:173      评论:0      收藏:0      [点我收藏+]

题目来源


https://leetcode.com/problems/balanced-binary-tree/

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.


题意分析


Input: a binary tree

Output: True or False

Conditions: 判断一颗树是不是平衡树,平衡树的意思是:对于每个节点而言,左右子树的最大深度不超过1


题目思路


递归判断。


AC代码(Python)

 1 # Definition for a binary tree node.
 2 # class TreeNode(object):
 3 #     def __init__(self, x):
 4 #         self.val = x
 5 #         self.left = None
 6 #         self.right = None
 7 
 8 class Solution(object):
 9     def Height(self, root):
10         if root == None:
11             return 0
12         return max(self.Height(root.left), self.Height(root.right)) + 1
13     def isBalanced(self, root):
14         """
15         :type root: TreeNode
16         :rtype: bool
17         """
18         if root == None:
19             return True
20         if abs(self.Height(root.left) - self.Height(root.right)) <= 1:
21             return self.isBalanced(root.left) and self.isBalanced(root.right)
22         else:
23             return False

 

[LeetCode]题解(python):110 Balanced Binary Tree

原文:http://www.cnblogs.com/loadofleaf/p/5502335.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!