Problem Definition:
Given a binary tree, determine if it is height-balanced.
For the problem, a height-balanced binary tree is defined as a
Binary tree in which the depth of the subtrees of the every node never differ by more than 1.
The problem here is that both the height of the subtree and the balance of the subtree should be recorded.
Solution 1: Only the sub-tree is balanced, and it is too time-consuming to recalculate the height each time.
Solution 2: Use a tuple to record height and balance.
1 #@param {TreeNode} root2 #@return {Boolean}3 defisbalanced (Root):4B,h=func (Root)5 returnb6 7 deffunc (Root):8 ifroot==None:9 return(true,0)TenLb,lh=func (Root.left) OneRb,rh=func (root.right) A return(ABS (LH-RH) <=1 andLb andRB, Max (LH,RH) +1) -
Solution 3: Combine the two variables and use a negative number to indicate the height of the imbalance.
1 defisbalanced (self, root):2 returnSelf.height (Root)!=-13 4 defheight (self,root):5 ifroot==None:6 return07Hl=self.height (root.left)8Hr=self.height (root.right)9 ifHl==-1orHr==-1orABS (HL-HR) >1:Ten return-1 One returnMax (HL,HR) +1
leetcode#110 Balanced Binary Tree