leetcode#110 Balanced Binary Tree

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.