二叉树的前序,中序,后序遍历
二叉树的节点数,叶子节点树的高度
#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;
}
二叉树的相关操作
最新推荐文章于 2023-01-01 14:46:04 发布
这篇博客介绍了二叉树的前序、中序、后序遍历方法,并提供了计算二叉树节点数、叶子节点数量及高度的实现。此外,还展示了交换二叉树左右子树的代码实现。
8362

被折叠的 条评论
为什么被折叠?



