附上原题:
Implement a function to check if a tree is balanced. For the purposes of this question, a balanced tree is defined to be a tree such that no two leaf nodes differ in distance from the root by more than one.
书上原题的解法:
public static int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
}
public static int minDepth(TreeNode root) {
if (root == null) {
return 0;
}
return 1 + Math.min(minDepth(root.left), minDepth(root.right));
}
public static boolean isBalanced(TreeNode root){
return (maxDepth(root) - minDepth(root) <= 1);
}
书上这段代码是有问题的,只判断了左右子树的深度差,却没有判断左右子树本身是不是平衡二叉树,代码应该为:
public static boolean isBalanced(TreeNode root){
return (isBalanced(root.left) && isBalanced(root.right) && maxDepth(root) - minDepth(root) <= 1);
}
但是这样也有问题,在判断左子树(右子树)是不是平衡二叉树的时候遍历了所有左(右)子节点,在maxDepth()又遍历了一遍,每一个叶子节点遍历了logn次,整体复杂度为O(n*logn)。
下面这段代码每个结点都只遍历一次,整体复杂度为O(n):
struct Data
{
bool isBalance;
int height;
};
Data isBalanced(TreeNode root){
Data value;
if(NULL == root)
{
value.isBalance = true;
value.height = 0;
}
else
{
Data left = isBalanced(root.left);
Data right = isBalanced(root.right);
value.isBalance = left.isBalance && right.isBalance && abs(left.height - right.height) <= 1;
value.height = max(left.height, right.height) + 1;
}
return value;
}
P.S. 函数名字isBalanced有点不太好,Don't mind this...