#include <iostream>
#include <string>
#include <vector>
#include <stack>
#include <stdio.h>
#include <time.h>

using namespace std;

struct Node
{
int data; // 节点中的数据
Node *m_pLeft;
Node *m_pRight;
};

Node* CreatNode(int value)
{
Node* pNode = new Node;
pNode->data = value;
return pNode;
}

void ConnectNodes(Node* pParent, Node* pLeft, Node* pRight)
{
if (pParent != nullptr)
{
pParent->m_pLeft = pLeft;
pParent->m_pRight = pRight;
}
}


void PrintNodeByLevel(Node* root)
{
if (root == nullptr)
{
return;
}

vector<Node*> NodeVec;
NodeVec.push_back(root);

int cur = 0;
int last = 1;

while (cur < NodeVec.size())//更新cur
{
last = NodeVec.size();//更新last
while (cur < last)//当前层的遍历输出
{
cout << NodeVec[cur]->data << " ";
if (NodeVec[cur]->m_pLeft)
{
NodeVec.push_back(NodeVec[cur]->m_pLeft);
}
if (NodeVec[cur]->m_pRight)
{
NodeVec.push_back(NodeVec[cur]->m_pRight);
}
cur++;
}
cout << endl;
}
}

int main()
{
// 1
// / \
// 2 3
// / \ \
// 4 5 6
// / \
// 7 8
Node *pNode1 = CreatNode(1);
Node *pNode2 = CreatNode(2);
Node *pNode3 = CreatNode(3);
Node *pNode4 = CreatNode(4);
Node *pNode5 = CreatNode(5);
Node *pNode6 = CreatNode(6);
Node *pNode7 = CreatNode(7);
Node *pNode8 = CreatNode(8);

ConnectNodes(pNode1, pNode2, pNode3);
ConnectNodes(pNode2, pNode4, pNode5);
ConnectNodes(pNode5, pNode7, pNode8);
ConnectNodes(pNode3, nullptr, pNode6);
ConnectNodes(pNode4, nullptr, nullptr);
ConnectNodes(pNode6, nullptr, nullptr);
ConnectNodes(pNode7, nullptr, nullptr);
ConnectNodes(pNode8, nullptr, nullptr);

PrintNodeByLevel(pNode1);

return 0;
}

分层遍历二叉树_遍历