编程之美。分层遍历二叉树(使用队列)

来源:互联网 发布:智能电话软件 编辑:程序博客网 时间:2024/05/22 06:19

层次遍历二叉树用队列是非常适合的,若需要打印出第n层的节点数据,只需要在队列中加入一个标记来分层(我使用的是NULL)


#include<iostream>
#include<queue>
using namespace std;
struct Node
{
 int t;
 Node *left, *right;
 Node(int t, Node * l = NULL, Node * r = NULL)
 {
  this->t = t;
  left = l;
  right = r;
 }
 Node()
 {
  left = NULL;
  right = NULL;
 }
};
int PrintNodeAtLevel(Node* root, int level)
{
 int res = 0;
 queue<Node*> qu;
 Node* p;
 qu.push(root);
 qu.push(NULL);
 int l = 0;//层数
 while (!qu.empty())
 {
  p = qu.front();
  qu.pop();
  if (p == NULL && !qu.empty())
  {
   l++;
   qu.push(NULL);
  }
  else if (p != NULL)
  {
   if (l == level)
   {
    cout << p->t;
    res = 1;
   }
   if (p->left != NULL)
    qu.push(p->left);
   if (p->right != NULL)
    qu.push(p->right);
  }
 }
 cout << endl;
 return res;
}
int main()
{
 Node* t7 = new Node(7);
 Node* t8 = new Node(8);
 Node* t5 = new Node(5, t7, t8);
 Node* t4 = new Node(4);
 Node* t2 = new Node(2, t4, t5);
 Node* t6 = new Node(6);
 Node* t3 = new Node(3,NULL,t6);
 Node* t1 = new Node(1, t2, t3);
 cout << PrintNodeAtLevel(t1, 4);
}

0 0