二叉树的基本操作
- 求节点个数
- 求叶子节点个数
- 求第K层节点个数
- 求二叉树高度
- 查找节点是否在树中
- 判断完全二叉树
- 求二叉树镜像
- 求节点个数
//采用后序遍历的方式,先计算左边,在计算右边,最后加上根结点
int GetSize(BTreeNode *root)
{
if(root == NULL)
{
return 0;
}
int left = GetSize(root->left);
int right = GetSize(root->right);
return left + right + 1;
}
- 求叶子节点个数
int GetLeafSize(BTreeNode *root)
{
if(root == NULL)
{
return 0;
}
//左右节点都为空,则为叶子节点
if(root->left == NULL && root->right == NULL)
{
return 1;
}
int left = GetLeafSize(root->left);
int right = GetLeafSize(root->right);
return left + right;
}
- 求第K层节点个数
int GetLevelSize(BTreeNode *root, TDataType k)
{
//对K的值进行断言
assert(k>=1);
if(root == NULL)
{
return 0;
}
if(k == 1)
{
return 1;
}
int left = GetLevelSize(root->left, k-1);
int right = GetLevelSize(root->right, k-1);
return left + right;
}
- 求二叉树高度
int GetHight(BTreeNode *root)
{
if(root == NULL)
{
return 0;
}
//只有根节点,树的高度为1
if(root->left == NULL && root->right == NULL)
{
return 1;
}
int left = GetHight(root->left);
int right = GetHight(root->right);
return (left>right)?left:right;
}
- 查找节点是否在树中
BTreeNode * Find(BTreeNode *root, TDataType data)
{
if(root == NULL)
{
return NULL;
}
if(root->data == data)
{
return root;
}
BTreeNode* result = Find(root->left,data);
if(result != NULL)
{
return result;
}
result = Find(root->right,data);
if(result != NULL)
{
return result;
}
else
{
return NULL;
}
}
- 判断完全二叉树
判断完全二叉树是根据层序遍历的思想来做的
int IsCompleteTree(BTreeNode *root)
{
Queue queue;
QueueInit(&queue);
BTreeNode *front;
QueuePush(&queue,root);
while(!QueueEmpty(&queue))
{
front = QueueFront(&queue);
QueuePop(&queue);
//当遇到空的时候停止
if(front == NULL)
{
break;
}
QueuePush(&queue,root->left);
QueuePush(&queue,root->right);
}
while(!QueueEmpty(&queue))
{
front = QueueFront(&queue);
QueuePop(&queue);
if(front != NULL)
{
QueueDestroy(&queue);
return 0;
}
}
QueueDestroy(&queue);
return;
}
- 求二叉树镜像
- 递归方式
void GetMirror(BTreeNode *root)
{
if(root == NULL)
{
return;
}
GetMirror(root->left);
GetMirror(root->right);
BTreeNode *temp = root->left;
root->left = root->right;
root->right = temp;
}
- 非递归方式(采用非递归的后序遍历)
void GetMirrorLoop(BTreeNode *root)
{
Stack stack;
StackInit(&stack);
BTreeNode *cur = root;
BTreeNode *top;
BTreeNode *last = NULL;
while(cur != NULL || !StackEmpty(&stack))
{
while(cur != NULL)
{
StackPush(&stack,cur);
cur = cur->left;
}
top = StackTop(&stack);
if(top->right == NULL || top->right == last)
{
StackPop(&stack);
BTreeNode *temp = root->left;
root->left = root->right;
root->right = temp;
last = top;
}
else
{
cur = top->right;
}
}
StackDestroy(&stack);
}