Implement a function to check if a binary tree is balanced. For the purposes of this question, a balanced tree is defined to be a tree such that the heights of the two subtrees of any node never differ by more than one.
There is a same problme on leetcode, https://oj.leetcode.com/problems/balanced-binary-tree/, you coud use this to test your code.
/* The idea comes from calculate the depth of a given binary tree. During the process, when would calculate all the subtrees' depth, then we could take advantage of this and judge at some point if the tree is valid or not, using a global var to store the result.*/ public class IsBalancedBinaryTree { boolean balance = true; public boolean isBalanced(TreeNode root) { balance = true; depth(root); return balance; } private int depth(TreeNode root) { if(root == null) return 0; else { int left = depth(root.left); int right = depth(root.right); if(Math.abs(left - right) > 1) balance = false; return Math.max(left, right) + 1; } } }