二叉树的一系列操作

BTNode* BinaryTreeCreate(BTDataType* a, int n, int* pi)
{
if (a[pi] != ‘#’)
{
BTNode
root=(BTNode*)malloc(sizeof(BTNode));
root->_data = a[*pi];
++(*pi);
root->_left=BinaryTreeCreate(a,n,pi);
++(*pi);
root->_right = BinaryTreeCreate(a, n, pi);
return root;
}
else
{
return NULL;
}
}

// 二叉树销毁
void BinaryTreeDestory(BTNode** root)
{
if ((root) == NULL)
{
return;
}
BinaryTreeDestory(&((root)->_left));
BinaryTreeDestory(&((root)->_right));
free(root);
root = NULL;
}
// 二叉树节点个数
int BinaryTreeSize(BTNode
root)
{
if (root == NULL)
return 0;
return BinaryTreeSize(root->_left) + BinaryTreeSize(root->_right)+1;
}
// 二叉树叶子节点个数
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);
}
// 二叉树第k层节点个数
int BinaryTreeLevelKSize(BTNode
root, int k)
{
if (root == NULL||k<1)
return 0;
if (k == 1)
return 1;
return BinaryTreeLevelKSize(root->_left, k - 1) + BinaryTreeLevelKSize(root->_right, k - 1);
}
// 二叉树查找值为x的节点
BTNode
BinaryTreeFind(BTNode* root, BTDataType x)
{
if (root == NULL)
return NULL;
if (root->_data == x)
return root;
BTNode* ret=BinaryTreeFind(root->_left, x);
if (ret)
return ret;
BinaryTreeFind(root->_right, x);
}
// 二叉树前序遍历
void BinaryTreePrevOrder(BTNode* root)
{
stack<BTNode*>sk;
while (root || !sk.empty())
{
if (root)
{
cout << root->_data;
sk.push(root);
root = root->_left;
}
else
{
root = sk.top();
sk.pop();
root = root->_right;
}
}
}
// 二叉树中序遍历
void BinaryTreeInOrder(BTNode* root)
{
stack<BTNode*>sk;
while (root || !sk.empty())
{
if (root)
{
sk.push(root);
root = root->_left;
}
else
{
root = sk.top();
sk.pop();
cout << root->_data;
root = root->_right;
}
}
}
// 二叉树后序遍历
void BinaryTreePostOrder(BTNode* root)
{
stack<BTNode*>sk;
BTNode* top=NULL;
BTNode* prev = NULL;
while (root || !sk.empty())
{
if (root)
{
sk.push(root);
root=root->_left;
}
else
{
root = sk.top();
if (root->_right== NULL || root->_right == prev)
{
cout << root->_data;
sk.pop();
prev = root;
root = NULL;
}
else
root = root->_right;
}
}
}
// 层序遍历
void BinaryTreeLevelOrder(BTNode* root)
{
queue<BTNode*>qu;
if (root == NULL)
return;
qu.push(root);
while (!qu.empty())
{
root = qu.front();
qu.pop();
cout << root->_data;
if (root->_left)
qu.push(root->_left);
if (root->_right)
qu.push(root->_right);
}
}
// 判断二叉树是否是完全二叉树
int BinaryTreeComplete(BTNode* root)
{
queue<BTNode*>que;
que.push(root);
while (!que.empty())
{
root = que.front();
que.pop();
if (root)
{
que.push(root->_left);
que.push(root->_right);
}
else
{
while (!que.empty())
{
if (que.front() != NULL)
return 0;
que.pop();
}
return 1;
}
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值