java 递归实现平衡二叉树

public class 平衡二叉树

{

public class TreeNode

{

TreeNode left;

TreeNode right;

int val;

TreeNode(int x)

{

this.val = x;

}

}

// 获取深度

private int getDepth(TreeNode tree, int currentDepth)

{

if (tree == null)

{

return currentDepth;

}

return Math.max(getDepth(tree.left, currentDepth + 1),

getDepth(tree.right, currentDepth + 1));

}

// 采用递归解决

public boolean isBalanced(TreeNode root)

{

if (root == null)

{

return true;

}

int depthOfLeft = getDepth(root.left, 1);

int depthOfRight = getDepth(root.right, 1);

if (Math.abs(depthOfLeft - depthOfRight) > 1)

{

return false;

}

else

{

return isBalanced(root.left) && isBalanced(root.right);

}

}

}