二叉树的相关操作

这篇博客介绍了二叉树的前序、中序、后序遍历方法,并提供了计算二叉树节点数、叶子节点数量及高度的实现。此外,还展示了交换二叉树左右子树的代码实现。

二叉树的前序,中序,后序遍历
二叉树的节点数,叶子节点树的高度

#include
#include
using namespace std;
//Á´Ê½´æ´¢
struct BiNode
{
char data;
BiNode* lchild, * rchild;
};
class BiTree
{
public:
BiTree() { root = Creat(); }
void PreOrder() { PreOrder(root); }
void InOrder() { InOrder(root); }
void PostOrder() { PostOrder(root); }
int Count() { return Count(root); }
int LeafCount() { return LeafCount(root); }
int HighCount() { return HighCount(root); }
void SwapTree() { SwapTree(root); }
private:
BiNode* root;
BiNode* Creat()
{
BiNode* root;
char ch;
cin >> ch;
if (ch == ‘#’)
root = NULL;
else
{
root = new BiNode;
root->data = ch;
root->lchild = Creat();
root->rchild = Creat();
}
return root;
}
void PreOrder(BiNode* root)
{
if (root == NULL)
return;
else
{
cout << root->data;
PreOrder(root->lchild);
PreOrder(root->rchild);
}
}
void InOrder(BiNode* root)
{
if (root == NULL)
return;
else
{
InOrder(root->lchild);
cout << root->data;
InOrder(root->rchild);
}
}
void PostOrder(BiNode* root)
{
if (root == NULL)
return;
else
{
PostOrder(root->lchild);
PostOrder(root->rchild);
cout << root->data;
}
}
int Count(BiNode* root)
{
int number = 0;
if (root == NULL)
number = 0;
else
number = Count(root->lchild) + Count(root->rchild) + 1;
return number;
}
int LeafCount(BiNode* root)
{
int number = 0;
if (root == NULL)
number = 0;
else if (root->lchild == NULL && root->rchild == NULL)
number = 1;
else
number = LeafCount(root->lchild) + LeafCount(root->rchild);
return number;
}
int HighCount(BiNode* root)
{
int number = 0;
if (root != NULL)
{
if (HighCount(root->lchild) > HighCount(root->rchild))
number = HighCount(root->lchild) + 1;
else
number = HighCount(root->rchild) + 1;
}
else
{
return 0;
}
return number;
}
void SwapTree(BiNode* root)
{
BiNode* temp;
if (root == NULL)
return;
else
{
temp = root->lchild;
root->lchild = root->rchild;
root->rchild = temp;
SwapTree(root->lchild);
SwapTree(root->rchild);
}
}
};
int main()
{
BiTree bt;
bt.PreOrder();
cout << endl;
cout << bt.Count() << endl;
cout << bt.LeafCount() << endl;
cout << bt.HighCount() << endl;
bt.SwapTree();
bt.PreOrder();
return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值