【劍指offer】判斷二叉樹平衡

蘭亭風雨發表於2014-05-28

轉載請註明出處:http://blog.csdn.net/ns_code/article/details/27242575

    題目:輸入一個二叉樹的根節點,判斷該樹是不是平衡二叉樹。如果某二叉樹中任意節點的左右子樹的深度相差不超過1,那麼它就是一棵平衡二叉樹。

    劍指offer上給的第二種思路,用後序遍歷真的是將遞迴發揮的淋漓盡致,先遍歷節點的左右子樹,左右子樹都平衡才來判斷該節點是否平衡,如果左右子樹中有不平衡的,則直接返回false,避免了從上往下逐個節點地計算深度帶來的重複遍歷節點。

    程式碼如下:

#include<stdio.h>
#include<stdlib.h>

typedef struct BTNode
{
	char data;
	struct BTNode *pLchild;
	struct BTNode *pRchild;
}BTNode, *BTree;

BTree create_tree();
bool IsBalanced(BTree,int *);
bool IsBalanced(BTree);

int main()
{
	BTree pTree = create_tree();
	if(IsBalanced(pTree))
		printf("Balanced\n");
	else
		printf("Not Balanced\n");

	return 0;
}

BTree create_tree()
{
	BTree pA = (BTree)malloc(sizeof(BTNode));
	BTree pB = (BTree)malloc(sizeof(BTNode));
	BTree pD = (BTree)malloc(sizeof(BTNode));
	BTree pE = (BTree)malloc(sizeof(BTNode));
	BTree pC = (BTree)malloc(sizeof(BTNode));
	BTree pF = (BTree)malloc(sizeof(BTNode));


	pA->data = 'A';
	pB->data = 'B';
	pD->data = 'D';
	pE->data = 'E';
	pC->data = 'C';
	pF->data = 'F';
	
	pA->pLchild = pB;
	pA->pRchild = pC;
	pB->pLchild = pD;
	pB->pRchild = pE;
	pD->pLchild = NULL;
	pD->pRchild = NULL;
	pE->pLchild = pE->pRchild = NULL;
	pC->pLchild = NULL;
	pC->pRchild = pF;
	pF->pLchild = pF->pRchild = NULL;	
	
	return pA;
}


/*
後續遞迴遍歷判斷二叉樹是否平衡
*/
bool IsBalanced(BTree pTree,int *depth)
{
	if(pTree == NULL)
	{
		*depth = 0;
		return true;
	}

	int leftDepth,rightDepth;
	if(IsBalanced(pTree->pLchild,&leftDepth) && IsBalanced(pTree->pRchild,&rightDepth))
	{
		int diff = leftDepth-rightDepth;
		if(diff<=1 && diff>=-1)
		{
			*depth = (leftDepth>rightDepth ? leftDepth:rightDepth) + 1;
			return true;
		}
	}
	return false;
}

/*
封裝起來
*/
bool IsBalanced(BTree pTree)
{
	int depth = 0;
	return IsBalanced(pTree,&depth);
}
    測試結果:



相關文章