#include<iostream>
#include<queue>
using namespace std;typedef char BTDataType;
struct BinaryTreeNode
{
BinaryTreeNode* left;
BinaryTreeNode* right;
BTDataType data;
};
typedef BinaryTreeNode BTNode;void PrevOrder(BTNode* root)//前序遍历
{
if (root == nullptr)
{
cout << "NULL" << " ";
return;
}cout << root->data << " ";
PrevOrder(root->left);
PrevOrder(root->right);
}void InOrder(BTNode* root)//中序遍历
{
if (root == nullptr)
{
cout << "NULL" << " ";
return;
}
InOrder(root->left);
cout << root->data << " ";
InOrder(root->right);
}void PostOrder(BTNode* root)//后序遍历
{
if (root == nullptr)
{
cout << "NULL" << " ";
return;
}
PostOrder(root->left);
PostOrder(root->right);
cout << root->data << " ";
}int TreeSize(BTNode* root)//树的结点个数
{
return root == nullptr ? 0 : TreeSize(root->left) + TreeSize(root->right) + 1;
}int TreeLeafSize(BTNode* root)//树的叶子结点个数
{
if (root == nullptr)
return 0;if (root->left == nullptr && root->right == nullptr)
return 1;return TreeLeafSize(root->left) + TreeLeafSize(root->right);
}void LevelOrder(BTNode* root)//层序遍历
{
queue<BTNode*>q;
if (root)
q.push(root);while (!q.empty())
{
BTNode* front = q.front();
q.pop();
cout << front->data << " ";if (front->left)
{
q.push(front->left);
}if (front->right)
{
q.push(front->right);
}
}cout << endl;
while (!q.empty())
{
q.pop();
}}
int main()
{
BTNode* A = new BTNode;
A->data = 'A';
A->left = nullptr;
A->right = nullptr;BTNode* B = new BTNode;
B->data = 'B';
B->left = nullptr;
B->right = nullptr;BTNode* C = new BTNode;
C->data = 'C';
C->left = nullptr;
C->right = nullptr;BTNode* D = new BTNode;
D->data = 'D';
D->left = nullptr;
D->right = nullptr;BTNode* E = new BTNode;
E->data = 'E';
E->left = nullptr;
E->right = nullptr;A->left = B;
A->right = C;B->left = D;
B->right = E;PrevOrder(A);
cout << endl;
InOrder(A);
cout << endl;
PostOrder(A);
cout << endl;cout << TreeSize(A) << endl;
cout << TreeSize(B) << endl;
cout << TreeSize(C) << endl;
cout << TreeLeafSize(C) << endl;LevelOrder(A);
}
二叉树的基本操作
最新推荐文章于 2024-10-10 22:04:37 发布