二叉树的构造代码

利用结构体定义二叉树轮廓:

typedef struct Tree
{
	int data;
	Tree* leftChild;
	Tree* rightChild;
}tree,*linklist;

创建二叉树:

void createtree(linklist node)
{
	int item;
	cin >> item;
	if(item == '#')
	    node = nullptr;
	else{
		node = (linklist)malloc(sizeof(tree));
		node->data = item;
		createtree(node->leftChild);
		createtree(node->rightChild);
	}    
}

销毁二叉树:

void destroytree(linklist node)
{
	if(node != nullptr)
	{
		destroytree(node->leftChild);
		destroytree(node->rightChild);
		free(node);
	}
}

利用递归方式(DFS)遍历二叉树的三种方法:

//先序遍历
void preOrder(linklist node)
{
	if(node != nullptr)
	{
		cout << node->data << ' ';
		preOrder(node->leftChild);
		preOrder(node->rightChild);
	}
}
//中序遍历
void inOrder(linklist node)
{
	if(node != nullptr)
	{
		inOrder(node->leftChild);
		cout << node->data << ' ';
		inOrder(node->rightChild);
	}
}
//后序遍历
void postOrder(linklist node)
{
	if(node != nullptr)
	{
		postOrder(node->leftChild);
		postOrder(node->rightChild);
		cout << node->data << ' ';
	}
}

利用队列(BFS)遍历二叉树:

//层序遍历
void levelOrder(linklist node)
{
	queue<linklist>q;
	q.push(node);
	linklist bt;	
	while(!q.empty())
	{
		bt = q.front();
		q.pop();
		cout << bt->data << ' ';
		if(bt->leftChild != nullptr)
		{
			q.push(bt->leftChild);
		}
		if(bt->rightChild != nullptr)
		{
			q.push(bt->rightChild);
		}
	}
}

最近更新

  1. TCP协议是安全的吗?

    2024-02-04 20:20:01       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-02-04 20:20:01       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-02-04 20:20:01       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-02-04 20:20:01       18 阅读

热门阅读

  1. C 练习实例55-学习使用按位取反~

    2024-02-04 20:20:01       18 阅读
  2. go使用gopprof分析内存泄露

    2024-02-04 20:20:01       33 阅读
  3. Go 语言实现并发、通道原理(附带案例)

    2024-02-04 20:20:01       32 阅读
  4. 自学PyQt6杂记索引

    2024-02-04 20:20:01       29 阅读
  5. Understanding TCP Congestion Control

    2024-02-04 20:20:01       28 阅读
  6. 数据库||数据库相关知识练习题目与答案

    2024-02-04 20:20:01       28 阅读