日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

面试题_分层遍历二叉树

發布時間:2025/3/15 编程问答 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 面试题_分层遍历二叉树 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

編程之美上的題目。

問題1:給定一棵二叉樹,要求按分層遍歷該二叉樹,即從上到下按層次訪問該二叉樹(每一行將單輸出一行),每一層要求訪問的順序為從左向右,并將節點依次編號。

問題2:寫一個函數,打印二叉樹中某層次的節點(從左向右),其中根結點為第1層。

#include<iostream>
#include
<queue>
using namespace std;

struct Tnode
{
Tnode
* leftChild;
Tnode
* rightChild;
int value;
Tnode():leftChild(NULL),rightChild(NULL)
{
value
=0;
}
Tnode(
int i):leftChild(NULL),rightChild(NULL)
{
value
=i;
}
};
//代碼之美上的。輸出第level層的所有元素
void printNodeAtLevel(Tnode * root, int level)
{
if(root==NULL||level<0)
{
return ;
}
if(level==1)
{
cout
<<root->value<<" ";
return ;
}
printNodeAtLevel(root
->leftChild,level-1);
printNodeAtLevel(root
->rightChild,level-1);
}

int main()
{
//建樹
Tnode * node1=new Tnode(1);
Tnode
* node2= new Tnode(2);
Tnode
* node3= new Tnode(3);
Tnode
* node4= new Tnode(4);
Tnode
* node5= new Tnode(5);
Tnode
* node6= new Tnode(6);
Tnode
* node7= new Tnode(7);
Tnode
* node8= new Tnode(8);
node1
->leftChild=node2;
node1
->rightChild=node3;
node2
->leftChild=node4;
node2
->rightChild=node5;
node3
->rightChild=node6;
node5
->leftChild=node7;
node5
->rightChild=node8;

//按層序遍歷二叉樹,并在每一層所有元素的后面打印一個換行符
//編程之美上寫的是類似遞歸的思想,其實也是在用遞歸棧來記錄層數,
//那么不如自己用個隊列來實時追蹤當前元素所在層
queue<Tnode*> que;
queue
<int> level;//用一個輔助隊列記錄當前元素的所在層
que.push(node1);
level.push(
1);
int currentLevel=1;
while(!que.empty())
{
Tnode
* temp=que.front();
que.pop();
int l=level.front();
level.pop();
if(currentLevel<l)
{
cout
<<endl;
currentLevel
=l;
}
cout
<<temp->value<<" ";
if(temp->leftChild!=NULL)
{
que.push(temp
->leftChild);
level.push(l
+1);
}
if(temp->rightChild!=NULL)
{
que.push(temp
->rightChild);
level.push(l
+1);
}
}
cout
<<endl;
// printNodeAtLevel(node1,3);
return 0;
}

轉載于:https://www.cnblogs.com/coser/archive/2011/03/31/2001592.html

總結

以上是生活随笔為你收集整理的面试题_分层遍历二叉树的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。