做网站淄博,沪上家居装修官网,网站开发九大优势,做微网站公司名称目录
前言
概述
接口
源码
测试函数
运行结果
往期精彩内容 前言
从前的日色变得慢#xff0c;车#xff0c;马#xff0c;邮件都慢#xff0c;一生,只够爱一个人。
概述
二叉树的层序遍历可以使用广度优先搜索#xff08;BFS#xff09;来实现。具体步骤如下车马邮件都慢一生,只够爱一个人。
概述
二叉树的层序遍历可以使用广度优先搜索BFS来实现。具体步骤如下 创建一个队列 queue并将根节点入队。 当队列不为空时重复执行以下步骤 a. 弹出队头元素并访问该节点。 b. 如果该节点有左子节点则将其左子节点入队。 c. 如果该节点有右子节点则将其右子节点入队。 当队列为空时说明已经遍历完整个二叉树。 以上是层序遍历的基本思想。
现在有二叉树如下
创建一个空的队列根节点入队弹出队头元素弹出即代表访问对该元素的操作根据实际需求编写即可访问该节点此节点有两个孩子那么B,C两个孩子入队
入队之后继续弹出一个元素B 访问该节点B节点只有一个左孩子没有右孩子左孩子D入队右孩子没有不入队。
又一次弹出元素访问此节点若有左右节点则入队否则不入队。直到队列为空 广度优先搜索BFS结束。 接口
void ergodic();
源码
#include malloc.h
#includestring.h
#includeiostream
using namespace std;class BINARYTREE
{
protected:struct NODESTRUCT{char data[15];struct NODESTRUCT* lChild;struct NODESTRUCT* rChild;};struct NODESTRUCT* treeRootnullptr;protected:struct data{struct NODESTRUCT* nodePtr;struct data* pre, *bk;};struct data* top, *button;private:struct NODESTRUCT* getPtrOfDataNode(char* data);
private:void push(struct NODESTRUCT* nodePtr);struct NODESTRUCT* pop();
public:BINARYTREE(){//队列初始化top button new struct data;button-pre nullptr;button-bk nullptr; }void ergodic();
};
void BINARYTREE::ergodic(){NODESTRUCT* nodePtr nullptr;if (treeRoot ! nullptr){push(treeRoot);while (true){nodePtr pop();if (nodePtr nullptr){break;}cout nodePtr-data endl;if (nodePtr-lChild ! nullptr){push(nodePtr-lChild);}if (nodePtr-rChild ! nullptr){push(nodePtr-rChild);}}}return;
}
测试函数 #includestdio.h #includeiostream using namespace std; #includeBINARYTREE.h #includewindows.h int main() { BINARYTREE binaryTree; binaryTree.initTree(); binaryTree.addLChild(A, B); binaryTree.addRChild(A, C); binaryTree.addLChild(B, D); binaryTree.addLChild(C, E); binaryTree.addRChild(C, F); binaryTree.ergodic(); system(pause); return 0; } 运行结果 往期精彩内容
数据结构第十二天队列