思想:
引入队列的概念
将28入队,队列不为空,将队首28元素取出,输出,将其左右两个节点入队:16 30
将队首16元素取出,输出,将其左右两个节点入队:30 13 22
将队首30元素取出,输出,将其左右两个节点入队:13 22 29 42
循环这样的操作,直到队列为空
结果:28 16 30 13 22 29 42
实现
//定义一棵二分搜索树
class BST{
private:
//树的一个节点定义
struct Node{
Key key;
Value value;
Node* left;//左孩子
Node* right;//右孩子
Node(Key key, Value value) //构造函数
{
this->key=key;
this->value=value;
this->right=this->left=NULL;
}
Node(Node* node) //构造函数
{
this->key=node->key;
this->value=node->value;
this->right=node->right;
this->left=node->left;
}
};
Node* root;//树的根节点
int count;//树的节点数
public:
BST()
{
count=0;
root=NULL;
}
int size()
{
return count;
}
bool isEmpty()
{
return count==0;
}
//层序遍历 使用队列的思想实现
void levelOrder()
{
queue<Node*> q;
q.push(root);
while(!q.empty())
{
//取出队首元素
Node * node=q.front();
q.pop();
cout<<node->key<<endl;
//将左右节点压入队列中
if(node->left!=NULL)
q.push(node->left);
if(node->right!=NULL)
q.push(node->right);
}
}
};
时间复杂度为O(n)