层次遍历二叉树
1.层次遍历二叉树:
从上往下的层次遍历:
struct TreeNode
{
int val;
TreeNode*pleft;
TreeNode*pright;
}
void PrintNodeatLevel(TreeNode *root,int level)
{
if(!root)
{
return;
}
vector<TreeNode *>vec;
vec.push_back(root);
int cur=0;
int last;
while(cur<vec.size())
{
last=vec.size();
while(cur<last)
{
cout<<vec[cur]->val<<' ';
vec.push_back(root->left);
vec.push_back(root->right);
cur++;
}
cout<<endl;
}
}
采用栈的写法:
void printTopDown(BinaryTree* root)
{
deque<BinaryTree> dequeB;
deque.push_back(root);
while(!deque.empty())
{
BinaryTree*p=deque.front();
cout<<p->value<<endl;
if(p->left)
dequeB.push_back(p->left);
if(p->right)
dequeB.push_back(p->right);
}
}
从下往上访问: