[Lintcode]93. Balanced Binary Tree/[Leetcode]
阿新 • • 發佈:2019-02-14
false it is lintcode diff des self etc desc not
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]