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.
/*** 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) {//you need to construct a function to calculate the height of a node, and then each layer of the isbalanced function starts to verify that the left and right sub-trees meet the requirements, and this idea is very intuitive.//This method is not efficient, because when each node is satisfied, it needs to be highly re-verified, then the next layer, the intermediate calculation has a repeating calculation//Another optimization algorithm, when the height of the information can be returned directly, the default direct return 1, do not need to compare if(root==NULL)return true; intleft=getdepth (Root.left); intright=getdepth (root.right); if(left>right+1| | RIGHT>LEFT+1)return false; Else{ returnisbalanced (Root.left) &&isbalanced (root.right); } } intgetdepth (TreeNode root) {if(root==NULL)return0; returnMath.max (Getdepth (Root.left), getdepth (root.right)) +1; } /*Public Boolean isbalanced (TreeNode root) {int temp=getdepth (root); Return temp>-1; } public int getdepth (TreeNode root) {if (root==null) return 0; int left=getdepth (root.left); int right=getdepth (root.right); int Temp=math.abs (left-right); if (left==-1| | right==-1| | temp>1) return-1; Return left>right?left+1:right+1; }*/}
[Leedcode] Balanced Binary Tree