【算法题】分层遍历二叉树

时间:2021-07-27 11:15:50
  • 使用双队列方式:一个队列表示当前层,一个队列表示下一层,
    换层时交换指向两队列的指针

#include <iostream>
#include <numeric>
#include<algorithm>
#include <queue>
using namespace std;

struct Tree
{
double value;
Tree* left;
Tree* right;
};

void Print(Tree* root)
{
if (root == NULL)
return;

queue<Tree*> queue_current;
queue<Tree*> queue_next;

auto * p_current = &queue_current;
auto * p_next = &queue_next;

Tree* p = root;
p_next->push(p);

while (!(*p_next).empty())
{
std::swap(p_current, p_next);
while (!(*p_current).empty())
{
p = p_current->front();
p_current->pop();
cout << p->value << " ";
if (p->left != NULL)
{
p_next->push(p->left);
}
if (p->right != NULL)
{
p_next->push(p->right);
}
}
cout << endl;
}
}

int main()
{
Tree root;
Tree node1_1;
Tree node1_2;
Tree node2_1;
Tree node2_2;
Tree node2_3;
Tree node3_1;
Tree node3_2;
Tree node3_3;
Tree node3_4;

root.value = 0;
node1_1.value = 1.1;
node1_2.value = 1.2;
node2_1.value = 2.1;
node2_2.value = 2.2;
node2_3.value = 2.3;
node3_1.value = 3.1;
node3_2.value = 3.2;
node3_3.value = 3.3;
node3_4.value = 3.4;

root.left = &node1_1;
root.right = &node1_2;

node1_1.left = &node2_1;
node1_1.right = &node2_2;

node1_2.left = &node2_3;
node1_2.right = NULL;

node2_1.left = &node3_1;
node2_1.right = &node3_2;

node2_2.left = NULL;
node2_2.right = NULL;

node2_3.left = &node3_3;
node2_3.right = &node3_4;

node3_1.left = NULL;
node3_1.right = NULL;

node3_2.left = NULL;
node3_2.right = NULL;

node3_3.left = NULL;
node3_3.right = NULL;

node3_4.left = NULL;
node3_4.right = NULL;

Print(&root);

return 0;
}

  • 使用单队列
    每一层,使用一个变量记录该层的结点个数,也就是队列的当前长度,然后依次在队列中访问该层的结点(将队列中len个元素出队列),并将下一层加入队列。
void Print(Tree* pRoot)
{
queue<Tree*> q;
if (!pRoot) return;

q.push(pRoot);

while (!q.empty())
{
int len = q.size();
while (len--)
{
Tree* tem = q.front();
q.pop();

cout << tem->value << " ";

if (tem->left) q.push(tem->left);
if (tem->right) q.push(tem->right);
}
cout << endl;
}
}