判断二叉树是否是平衡树

解法1:

int TreeDepth(BinaryTreeNode* pRoot)
{
    if(pRoot == NULL)
        return 0;

    int nLeft = TreeDepth(pRoot->m_pLeft);
    int nRight = TreeDepth(pRoot->m_pRight);

    return (nLeft > nRight) ? (nLeft + 1) : (nRight + 1);
}

bool IsBalanced_Solution1(BinaryTreeNode* pRoot)
{
    if(pRoot == NULL)
        return true;

    int left = TreeDepth(pRoot->m_pLeft);
    int right = TreeDepth(pRoot->m_pRight);
    int diff = left - right;
    if(diff > 1 || diff < -1)
        return false;

    return IsBalanced_Solution1(pRoot->m_pLeft) 
        && IsBalanced_Solution1(pRoot->m_pRight);
}

解法2:

struct BinaryTreeNode{
	int m_nValue;
	BinaryTreeNode *m_pLeft;
	BinaryTreeNode *m_pRight;
};

bool isAVL(BinaryTreeNode *pRoot, int &height){
	if(pRoot == NULL){
		height = 0;
		return true;
	}
	int leftHeight, rightHeight;
	bool leftResult = isAVL(pRoot->m_pLeft, leftHeight);
	bool rightResult = isAVL(pRoot->m_pRight, rightHeight);
	if(leftResult && rightResult && abs(leftHeight - rightHeight) <= 1){
		height = 1 + (leftHeight > rightHeight ? leftHeight : rightHeight);
		return true;
	}
	else{
		height = 1 + (leftHeight > rightHeight ? leftHeight : rightHeight);
		return false;
	}
}


你可能感兴趣的:(判断二叉树是否是平衡树)