实现一个函数,检查二叉树是否平衡。
二叉树平衡的定义如下:任意一个结点,其两颗子树的高度差不超过1
递归访问每个整棵树,计算每个结点子树的高度
- public class BTreeBalanced {
- static class TreeNode {
- int data;
- static TreeNode left;
- static TreeNode right;
- }
- public static boolean isBalanced(TreeNode root) {
- if (null == root) return true;
- int heightDiff = getHeight(root.left) - getHeight(root.right);
- if ( Math.abs(heightDiff) > 1 ) {
- return false;
- }
- else {
- return ( isBalanced(TreeNode.left) && isBalanced(TreeNode.right) );
- }
- }
- public static int getHeight(TreeNode root) {
- if (null == root) return 0;
- return Math.max( getHeight(root.left), getHeight(root.right) + 1 );
- }
- }
但这样做的效率不高,getHeight()会被反复调用计算同一个结点的高度,时间复杂度为O(N logN)
getHeight()其实不仅可以检查高度,还能检查树是否平衡,只要将判断左右子树高度差是否大于一放进getHeight()就可以了,下面用checkHeight()来表示这一段代码。
这样做的好处是时间复杂度降低了,为O(N),空间复杂度为O(H),H为树的高度
- public static int checkHeight(TreeNode root) {
- if (null == root) return 0;
- int leftHeight = checkHeight(root.left);
- if ( leftHeight == -1 ) {
- return -1;
- }
-
- int rightHeight = checHeight(root.right);
- if ( rightHeight == -1 ) {
- return -1;
- }
-
- int heightDiff = leftHeight - rightHeight;
- if (Math.abs(heightDiff) > 1) {
- return -1;
- }
- else {
- return Math.max( rightHeight, rightHeight + 1 );
- }
- }
- public static boolean isBalanced2(TreeNode root) {
- if(checkHeight(root) == -1) {
- return false;
- }
- else {
- return true;
- }
- }