代码如下:
#include <iostream>
#include <vector>
using namespace std;
typedef struct Node
{
int data;
Node* pLeft;
Node* pRight;
Node(const int& data) {
this->data = data;
pLeft = NULL;
pRight = NULL;
}
} *PNode;
void printTreeByLevel(PNode node) {
vector<PNode> vec;
if (node == NULL) {
return;
}
vec.push_back(node);
int i = 0;
int preCount = 1;
int count = 0;
int cur = 0;
while (i < vec.size()) {
cout << vec[i]->data << " ";
if (vec[i]->pLeft != NULL)
{
vec.push_back(vec[i]->pLeft);
count++;
}
if (vec[i]->pRight != NULL)
{
vec.push_back(vec[i]->pRight);
count++;
}
i++;
if (i - cur == preCount)
{
cout << endl;
preCount = count;
cur = i;
count = 0;
}
}
cout << endl;
}
void main() {
PNode node1 = new Node(1);
PNode node2 = new Node(2);
PNode node3 = new Node(3);
node1->pLeft = node2;
node1->pRight = node3;
PNode node4 = new Node(4);
PNode node5 = new Node(5);
node2->pLeft = node4;
node2->pRight = node5;
PNode node6 = new Node(6);
node3->pRight = node6;
PNode node7 = new Node(7);
PNode node8 = new Node(8);
node5->pLeft = node7;
node5->pRight = node8;
PNode node9 = new Node(9);
PNode node10 = new Node(10);
node6->pLeft = node9;
node6->pRight = node10;
PNode node11 = new Node(11);
node7->pLeft = node11;
PNode node12 = new Node(12);
node8->pRight = node12;
printTreeByLevel(node1);
getchar();
}
解法二:
void printTreeLevel(TreeNode* root)
{
vector<TreeNode*> vec;
vec.push_back(root);
int cur = 0;
int last = 1;
while (cur < vec.size())
{
int count = 0;
while (cur < last)
{
cout << vec[cur]->m_data<<" ";
if (vec[cur]->pLChild != NULL)
{
count++;
vec.push_back(vec[cur]->pLChild);
}
if (vec[cur]->pRChild != NULL)
{
count++;
vec.push_back(vec[cur]->pRChild);
}
cur++;
}
last += count;
cout << endl;
}
}
方法三:
vector<vector<int> > PrintNew(TreeNode* pRoot) {
vector<vector<int> > vecList;
queue<TreeNode*> queList;
queList.push(pRoot);
while (queList.size() > 0)
{
int start = 0;
int end = queList.size();
vector<int> vec;
while (start < end)
{
TreeNode* node = queList.front();
queList.pop();
vec.push_back(node->m_data);
if (node->pLChild != NULL)
{
queList.push(node->pLChild);
}
if (node->pRChild != NULL)
{
queList.push(node->pRChild);
}
++start;
}
vecList.push_back(vec);
}
return vecList;
}
引自《编程之美》
网友评论