[Cracking the coding interview]判断一棵树是否平衡

问题定义:

        Implement a function to check if a tree is balaned. For the purpose 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.

思路:

        分别判断左子树是不是平衡的,返回左子树的深入,同理,判断右子树是不是平衡的,返回右子树的深度,如果左右子树的深度之差不超过1,则说明现在的树是平衡的。

方法如下(构造树的部分可以参见http://blog.csdn.net/lalor/article/details/7613621):

////只遍历二叉树一一遍的方法,在已知子树不平衡的情况下,则直接返回false
bool isBalanced(struct node *root, int *depth)
{
	if (root == NULL) 
	{
		*depth = 0;
		return true;
	}

	int left, right;
	if (isBalanced2(root->lchild, &left) && isBalanced2(root->rchild, &right)) 
	{
		int diff = left - right;
		if (diff <=1 || diff >= -1) 
		{
			*depth = 1 + (left > right ? left : right);
			return true;
		}
	}
	return false;	
}


你可能感兴趣的:(function,struct,tree,null,distance)