[Lintcode]93. Balanced Binary Tree/[Leetcode]
Posted siriusli
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Lintcode]93. Balanced Binary Tree/[Leetcode]相关的知识,希望对你有一定的参考价值。
93. Balanced Binary Tree/
- 本题难度: Easy
- Topic: 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.
Example
Example 1:
Input: tree = {1,2,3}
Output: true
Explanation:
This is a balanced binary tree.
1
/
2 3
Example 2:
Input: tree = {3,9,20,#,#,15,7}
Output: true
Explanation:
This is a balanced binary tree.
3
/
9 20
/
15 7
Example 3:
Input: tree = {1,#,2,3,4}
Output: false
Explanation:
This is not a balanced tree.
The height of node 1‘s right sub-tree is 2 but left sub-tree is 0.
1
2
/
3 4
我的代码
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param root: The root of binary tree.
@return: True if this Binary tree is Balanced, or false.
"""
def balancehigh(self,root):
if root is None:
return 0
left = self.balancehigh(root.left)
right = self.balancehigh(root.right)
if left == -1 or right == -1 or abs(left-right)>1:
return -1
return 1+max(left,right)
def isBalanced(self, root):
# write your code here
return self.balancehigh(root)!=-1
思路
仍然是递归。
当一个子树不平衡时,整个二叉树肯定不平衡,否则记录其高度。
以上是关于[Lintcode]93. Balanced Binary Tree/[Leetcode]的主要内容,如果未能解决你的问题,请参考以下文章
lintcode-medium-Balanced Binary Tree
Lintcode106.Convert Sorted List to Balanced BST
平衡二叉树(Balanced Binary Tree 或 Height-Balanced Tree)又称AVL树