图的创建与遍历(C++)

最近复习到了数据结构中的图这一章,随手整理了些图的创建与遍历的完整代码,如下所示:#include using namespace std;#define maxSize 100typedef struct { int no; //顶点编号 char info; //顶点其他信息}VertexType;typedef struct { int edges[maxS
摘要由CSDN通过智能技术生成

最近复习到了数据结构中的图这一章,随手整理了些图的创建与遍历的完整代码,如下所示:

#include 
   
   
    
    
using namespace std;
#define maxSize 100

typedef struct 
{
	int no;	//顶点编号
	char info;	//顶点其他信息
}VertexType;
typedef struct 
{
	int edges[maxSize][maxSize];
	int n,e;
	VertexType vex[maxSize];
}MGraph;//图的邻接矩阵

typedef struct ArcNode//结点信息
{
	int adjvex;
	struct ArcNode *nextarc;
	int info;
}ArcNode;
typedef struct VNode//头结点或链表信息
{
	char data;
	ArcNode *firstarc;
}VNode;
typedef struct 
{
	VNode adjlist[maxSize];//邻接表
	int n,e;//顶点数,边数
}AGraph;//图的邻接表

//基本变量
int visit[maxSize] = {0};
void DFS(AGraph *G,int v);//深度优先搜索
void BFS(AGraph *G,int v);//广度优先搜索
int createGraph(AGraph &graph);//创建图
int getIndex(AGraph graph,int data);//由结点值得到索引

void main()
{
	AGraph graph;
	int ret = createGraph(graph);
	if(ret==1)
	{
		/*cout<<"深度优先搜索"<
    
    
     
     >graph.n&g
  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
以下是C++中二叉树的创建遍历的示例代码: ```c++ #include <iostream> using namespace std; // 二叉树结点的定义 struct TreeNode { int val; TreeNode* left; TreeNode* right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; // 创建二叉树 TreeNode* createTree() { int val; cin >> val; if (val == -1) { // 如果输入-1,表示该结点为空结点 return NULL; } TreeNode* root = new TreeNode(val); root->left = createTree(); // 递归创建左子树 root->right = createTree(); // 递归创建右子树 return root; } // 前序遍历 void preOrder(TreeNode* root) { if (root == NULL) { return; } cout << root->val << " "; // 输出结点的值 preOrder(root->left); // 递归遍历左子树 preOrder(root->right); // 递归遍历右子树 } // 中序遍历 void inOrder(TreeNode* root) { if (root == NULL) { return; } inOrder(root->left); // 递归遍历左子树 cout << root->val << " "; // 输出结点的值 inOrder(root->right); // 递归遍历右子树 } // 后序遍历 void postOrder(TreeNode* root) { if (root == NULL) { return; } postOrder(root->left); // 递归遍历左子树 postOrder(root->right); // 递归遍历右子树 cout << root->val << " "; // 输出结点的值 } int main() { TreeNode* root = createTree(); // 创建二叉树 cout << "前序遍历结果:"; preOrder(root); // 前序遍历 cout << endl; cout << "中序遍历结果:"; inOrder(root); // 中序遍历 cout << endl; cout << "后序遍历结果:"; postOrder(root); // 后序遍历 cout << endl; return 0; } ```
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值