bool isBalanceTree(TreeNode* node, int& height) { if (!node) { height = 0; return true; } int left_hegiht; bool left = isBalanceTree(node->left, left_hegiht); int right_height; bool right = isBalanceTree(node->right, right_height); if (left && right && abs(left_hegiht-rihgt_height) <= 1) return true; else return false; }
int isBalanceTree(BSTree T) { if ( T == NULL ) { return TRUE; } int depthLeft = GetBSTreeDepth(T->lchild); int depthRight = GetBSTreeDepth(T->rchild); if (abs( depthLeft - depthRight ) > 1) { return FALSE; } else { return (isBalanceTree(T->lchild) == TRUE ) && (isBalanceTree(T->rchild) == TRUE ); } }
int main(int argc, char* argv[]) { const char* str1 = "124##57###3#6##"; Node* root1 = initBinaryTree(str1); assert(getBinaryTreeDeep(root1) == 4); assert(isBalanceTree(root1)); const char* str2 = "5321###4##76##8##"; Node* root2 = initBinaryTree(str2); assert(getBinaryTreeDeep(root2) == 4); assert(isBalanceTree(root2)); const char* str3 = "123####"; Node* root3 = initBinaryTree(str3); assert(getBinaryTreeDeep(root3) == 3); assert(!isBalanceTree(root3)); printf("all test case passed!\n"); return 0; }