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.
Problem Solving Ideas:
Recursively calculates the depth of the left and right subtree of each node to see if it is balanced.
The calculation of the depth of left and right subtree can be referred to the recursive solution of maximum Depth of Binary tree.
Java Code:
/*** Definition for a binary tree node. * public class TreeNode {* int val; * TreeNode left; * TreeNode rig Ht * TreeNode (int x) {val = x;} }*/ Public classSolution { Public Booleanisbalanced (TreeNode root) {if(Root = =NULL) { return true; } intdiff = maxDepth (root.left)-maxDepth (root.right); if(diff > 1 | | diff <-1 ) { return false; } returnisbalanced (Root.left) &&isbalanced (root.right); } Public intmaxDepth (TreeNode root) {//Use recursion if(Root = =NULL) { return0; } intLeftmax =maxDepth (Root.left); intRightmax =maxDepth (root.right); returnMath.max (Leftmax, Rightmax) + 1; }}
Reference:
1. http://www.cnblogs.com/infinityu/archive/2013/05/11/3073411.html
Leetcode Balanced Binary Tree