二叉树的定义
typedef struct node{
struct node *left, *right;
int val;
}Node, *BinTree;
非递归实现二叉树的层序遍历:
void PrintTree(BinTree root)
{
if(!root)
return;
queue<Node *> q;
q.push(root);
BinTree p = root;
while(!q.empty())
{
p = q.front();
cout<<p->val<<" ";
q.pop();
if(p->left)
q.push(p->left)
if(p->right)
q.push(p->right)
}
}
非递归实现二叉树的层序遍历且每层各占一行:
void PrintTreeLevel(BinTree root)
{
if(root == NULL)
return;
vector<Node *> vec;
vec.push_back(root);
int cur = 0;
int last = 1;
while(cur < vec.size())
{
last = vec.size();
while(cur < last)//为了分层输出
{
cout<<vec[cur]->val<<" ";
if(vec[cur]->left != NULL)
vec.push_back(vec[cur]->left);
if(vec[cur]0>right != NULL)
vec.push_back(vec[cur]->right);
cur++;
}
cout<<endl;
}
}
递归实现二叉树的层序遍历:
class Solution {
public:
vector<vector<int>> levelorder(BinTree root)
{
vector<vector<int>> result;
level(result, root, 1);
return result;
}
}
void level(vector<vector<int>> &result, BinTree root, int num)
{
if(root ==NULL)
return;
if(num > result.size())
result.push_back(vector<int>());
result[num - 1].push_back(root->val);
level(result, root->left, num+1);
level(result, root->right. num+1);
}