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.
Subscribe to see which companies asked this question
1 /**2 * Definition for a binary tree node.3 * public class TreeNode {4 * int val;5 * TreeNode left;6 * TreeNode right;7 * TreeNode (int x) {val = x;}8 * }9 */Ten Public classSolution { One Public Booleanisbalanced (TreeNode root) { A returnHeight (root)! =-1; - } - the Public intheight (TreeNode t) { - if(T = =NULL)return0and/ /to the leaf node again down the situation - intLheight =height (t.left); - intRheight =height (t.right); + if(Lheight = =-1 | | rheight = =-1 | | Math.Abs (lheight-rheight) > 1){ - return-1;//Use -1 to mark the height difference between the left and right sub-trees is greater than 1 + } A return1 +Math.max (lheight,rheight); at } -}
Balanced Binary Tree Java Solutions