typedef char BTDataType;
typedef struct BinaryTreeNode
{
BTDataType _data;
struct BinaryTreeNode* _left;
struct BinaryTreeNode* _right;
}BTNode;
BTNode* BinaryTreeCreate(BTDataType* a, int n, int* pi)
{
if (a[*pi] == '#')
return NULL;
else
{
BTNode* root = (BTNode*)malloc(sizeof(BTNode));
root->_data = a[*pi];
++(*pi);
root->_left = Rebuild(a, pi);
++(*pi);
root->_right = Rebuild(a, pi);
return root;
}
}
void BinaryTreeDestory(BTNode* root)
{
if (root == NULL)
return;
BinaryTreeDestory(root->_left);
BinaryTreeDestory(root->_right);
free(root);
}
int BinaryTreeSize(BTNode* root)
{
if (root == NULL)
return 0;
return 1 + BinaryTreeSize(root->_left) + BinaryTreeSize(root->_right);
}
int BinaryTreeLeafSize(BTNode* root)
{
if (root == NULL)
return 0;
if (root->_left == NULL && root->_right == NULL)
return 1;
return BinaryTreeLeafSize(root->_left) +BinaryTreeLeafSize(root->_right);
}
int BinaryTreeLevelKSize(BTNode* root, int k)
{
if (root == NULL)
return 0;
if (k == 1)
return 1;
return BinaryTreeLevelKSize(root, k-1) + BinaryTreeLevelKSize(root, k-1);
}
BTNode* BinaryTreeFind(BTNode* root, BTDataType x)
{
BTNode* ret;
if (root == NULL)
return NULL;
if (root->_data == 'x')
return root;
ret = BinaryTreeFind(root->_left, x);
if (ret)
return ret;
ret = BinaryTreeFind(root->_left, x);
if (ret)
return ret;
return NULL;
}
void BinaryTreePrevOrder(BTNode* root)
{
if (root == NULL)
return;
printf("%c", root);
BinaryTreePrevOrder(root->_left);
BinaryTreePrevOrder(root->_right);
}
void BinaryTreeInOrder(BTNode* root)
{
if (root == NULL)
return;
BinaryTreePrevOrder(root->_left);
printf("%c", root->_data);
BinaryTreePrevOrder(root->_right);
}
void BinaryTreePostOrder(BTNode* root)
{
if (root == NULL)
return;
BinaryTreePrevOrder(root->_left);
BinaryTreePrevOrder(root->_right);
printf("%c", root);
}
void BinaryTreeLevelOrder(BTNode* root)
{
Queue q;
QueueInit(&q);
if (root != NULL)
{
QueuePush(&q, root);
}
while (!QueueEmpty(&q))
{
BTNode* front = QueueFront(&q);
QueuePop(&q);
print("%c ", front->_data);
if (root->_left)
{
QueuePush(&q, root->_left);
}
if (root->_right)
{
QueuePush(&q, root->_right);
}
}
printf("\n");
QueueDestroy(&q);
}
int BinaryTreeComplete(BTNode* root)
{
Queue q;
QueueInit(&q);
if (root != NULL)
{
QueuePush(&q, root);
}
while (!QueueEmpty(&q))
{
BTNode* front = QueueFront(&q);
QueuePop(&q);
if (front == NULL)
break;
QueuePush(&q, root->_left);
QueuePush(&q, root->_right);
}
while (!QueueEmpty(&q))
{
BTNode* front = QueueFront(&q);
QueuePop(&q);
if (front != NULL)
{
return 0;
}
}
return 1;
}