#include<iostream>
#include<stdlib.h>
class TreeNode
{
public:
void SetTreeNode(char name,int num = 0,TreeNode* left=nullptr,TreeNode* right=nullptr)
{
Name = name;
Data = num;
LChild = left;
RChild = right;
}
TreeNode* GetTreeNode()
{
return this;
}
int GetTreeNodeData()
{
return Data;
}
char GetTreeNodeName()
{
return Name;
}
void SetTreeLeftChild(TreeNode* left)
{
if (this->LChild == nullptr)
{
this->LChild = left;
}
else
{
std::cout << "设置出错,已存在左孩子" << std::endl;
}
}
void SetTreeRightChild(TreeNode* right)
{
if (this->RChild == nullptr)
{
this->RChild = right;
}
else
{
std::cout << "设置出错,已存在右孩子" << std::endl;
}
}
TreeNode* GetTreeLeftChild()
{
return LChild;
}
TreeNode* GetTreeRightChild()
{
return RChild;
}
private:
char Name;
int Data;
TreeNode* LChild;
TreeNode* RChild;
};
TreeNode* CreateTreeNode(char name,int num=0, TreeNode* left = nullptr, TreeNode* right = nullptr)
{
TreeNode* node=new TreeNode;
node->SetTreeNode(name,num,left,right);
return node->GetTreeNode();
}
void FPrint(TreeNode* node)
{
std::cout << node->GetTreeNodeName()<<":"<<node->GetTreeNodeData() << " ";
if (node->GetTreeLeftChild() != nullptr)
FPrint(node->GetTreeLeftChild());
if (node->GetTreeRightChild() != nullptr)
FPrint(node->GetTreeRightChild());
}
void IPrint(TreeNode* node)
{
if (node->GetTreeLeftChild() != nullptr)
IPrint(node->GetTreeLeftChild());
std::cout << node->GetTreeNodeName() << ":" << node->GetTreeNodeData() << " ";
if (node->GetTreeRightChild() != nullptr)
IPrint(node->GetTreeRightChild());
}
void LPrint(TreeNode* node)
{
if (node->GetTreeLeftChild()!=nullptr)
LPrint(node->GetTreeLeftChild());
if (node->GetTreeRightChild()!=nullptr)
LPrint(node->GetTreeRightChild());
std::cout << node->GetTreeNodeName() << ":" << node->GetTreeNodeData() << " ";
}
int main()
{
TreeNode* TopA = CreateTreeNode('A',1);
TreeNode* B = CreateTreeNode('B',2);
TreeNode* C = CreateTreeNode('C',3);
TreeNode* D = CreateTreeNode('D',4);
TreeNode* E = CreateTreeNode('E',5);
TreeNode* F = CreateTreeNode('F',6);
TreeNode* G = CreateTreeNode('G',7);
TopA->SetTreeLeftChild(C); /* A */
TopA->SetTreeRightChild(F); /* / \ */
C->SetTreeLeftChild(G); /* C F */
C->SetTreeRightChild(D); /* / \ \ */
F->SetTreeRightChild(B); /* G D B */
B->SetTreeLeftChild(E); /* / */
/* E */
std::cout << "前序:";
FPrint(TopA);
std::cout << std::endl;
std::cout << "中序:" ;
IPrint(TopA);
std::cout << std::endl;
std::cout << "后序:" ;
LPrint(TopA);
std::cout << std::endl;
system("pause");
return 0;
}
吾也爱C++_树的遍历(前序-中序-后序)
最新推荐文章于 2023-01-25 14:51:23 发布