【面经】二叉树层次遍历

1、递归:  输出某指定层

 1 //输出以root为跟节点中的第level层中的所有节点(从左到右),成功返回1,
 2 //失败返回0,
 3 //@param
 4 //root为二叉树的根节点
 5 //level为层次节点,其中根节点为第0层
 6 int printNodeAtLevel(Node *root, int level)
 7 {
 8     if(!root || level < 0)
 9         return 0;
10     if(level == 0)
11     {
12         cout<<root->data<<" ";
13         return 1;
14     }      
15     return printNodeAtLevel(root->lChild, level-1) + printNodeAtLevel(root->rChild,level-1);
16 }

2、【转】遍历当前层的时候,保存下一层的节点数,只需要每次插入一个节点的时候childSize++即可,这样我们就知道下一层有几个节点了,然后将childSize赋值给parentSize,开始新的一层遍历,从队列中取出parentSize个节点以后,也就知道这一层遍历完了。

 1 void printNodeAtLevel(Node *root)
 2 {
 3     int parentSize = 1, childSize = 0;
 4     Node *temp;
 5     queue<Node *> q;
 6     q.push(root);
 7     do
 8     {
 9         temp = q.front();
10         cout<<temp->data<<" ";
11         q.pop();
12   
13         if(temp->lChild != NULL)
14         {
15             q.push(temp->lChild);
16             childSize ++;
17         }
18         if(temp->rChild != NULL)
19         {
20             q.push(temp->rChild);
21             childSize ++;
22         }
23 
24         parentSize --;
25         if(parentSize == 0)
26         {
27                 parentSize = childSize;
28                 childSize = 0;
29                 cout<<endl;
30         }
31     }while(!q.empty());
32 }

 

posted @ 2016-04-20 15:49  QoQzz  阅读(206)  评论(0编辑  收藏  举报