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.
The depth of each subtree can be calculated first and then compared. However, it is not efficient and the time complexity is O (NLGN). Because each time the left and right subtree depth is 2*o (LGN), then recursion n times.
Public BOOLisbalanced (TreeNode root) {if(Root = =NULL)return true; intleft =treeheight (Root.left); intright =treeheight (root.right); if((left>=right+2)|| (left+2<=right))return false; returnisbalanced (Root.left) &&isbalanced (root.right); } Public inttreeheight (TreeNode root) {if(Root = =NULL)return 0; if(Root.left = =NULL&& Root.right = =NULL)return 1; returnMath.max (Treeheight (Root.left), Treeheight (root.right)) +1; }
The optimized method is DFS, check whether the smaller subtree is balanced Tree, and if not, return false directly. Reference http://www.cnblogs.com/grandyang/p/4045660.html
Public BOOLisbalanced (TreeNode root) {return! (Treeheight (Root) ==-1); } Public inttreeheight (TreeNode root) {if(Root = =NULL)return 0; intleft =treeheight (Root.left); if(left = =-1)return-1; intright =treeheight (root.right); if(Right = =-1)return-1; if((left>=right+2)|| (left+2<=right))return-1; returnMath.max (left, right) +1; }
Balanced Binary Tree