lintcode-medium-balanced Binary Tree

Source: Internet
Author: User

Given a binary tree, determine if it is height-balanced.

For this problem, a height-balanced binary tree was defined as a binary tree in which the depth of the Every node never differ by more than 1.

Given binary Tree a= {3,9,20,#,#,15,7} , b={3,#,20,15,7}

A)  3            B)    3    /\                    9    /  \                /   7  7

The binary tree A is a height-balanced binary tree, but B is not.

/*** Definition of TreeNode: * public class TreeNode {* public int val; * Public TreeNode left, right; * PU Blic TreeNode (int val) {* This.val = val; * This.left = This.right = null; *} *}*/ Public classSolution {/**     * @paramroot:the root of binary tree. * @return: True If this Binary tree is Balanced, or false. */     Public Booleanisbalanced (TreeNode root) {//Write your code here                if(Getdepth (root)! =-1)            return true; Else             return false; }         Public intgetdepth (TreeNode root) {if(Root = =NULL)            return0; intleft =getdepth (Root.left); intright =getdepth (root.right); if(Math.Abs (left-right) > 1)            return-1; if(left = =-1 | | right =-1)            return-1; returnMath.max (left, right) + 1; }}

lintcode-medium-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.