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