[英]Why isn't my printLevel function working?
我已編寫此代碼來執行二進制搜索樹的級別順序遍歷。 僅在printLevel函數中有錯誤,因為所有其他函數都工作正常。
#include <queue>
using namespace std;
struct node{
int data;
struct node* left;
struct node* right;
};
struct node* newNode(int data){
struct node* node = new (struct node);
node->data=data;
node->left=NULL;
node->right=NULL;
return (node);
};
struct node* insert (struct node* node, int data){
if (node==NULL){
return (newNode(data));
}
else {
if (data<=node->data) node-> left=insert(node->left,data);
else node->right=insert(node->right,data);
return (node);
}
}
void printLevel(struct node* node){
queue<struct node*> q;
while(node!=NULL){
cout << node->data << " ";
q.push(node->left);
q.push(node->right);
node=q.front();
}
}
int main(){
int n;
cin >>n;
int m;
cin >>m;
struct node* root=newNode(m);
for (int i=0;i<n-1;i++){
cin>>m;
insert(root,m);
}
printLevel(root);
// printPostOrder(root);
// cout <<maxDepth(root);
// debug(maxDepth(root), minValue(root), printTree(root));
//struct node* root=build123();
}
算法如下:( http://www.geeksforgeeks.org/level-order-tree-traversal/ )
printLevelorder(tree)
1)創建一個空隊列q
2)temp_node = root / 從root開始
3)temp_node不為NULL時循環
a) print temp_node->data.
b) Enqueue temp_node’s children (first left then right children) to q
c) Dequeue a node from q and assign it’s value to temp_node
我正在為7個節點輸入3、1、4、2、7、6、5。 它陷入無限循環。 我還基於另一種方法實現了以下兩個功能,並且運行良好:
void levelOrder(struct node* node, int level ){
if (node==NULL){
return;
}
if (level==1){
cout << node->data;
}
else if (level>1){
levelOrder(node->left,level-1);
levelOrder(node->right,level-1);
}
}
void printLevelOrder(struct node* root){
for (int i=1;i<=maxDepth(root);i++){
levelOrder(root,i);
}
}
它是O(n ^ 2),但大於1的是O(n)。 我的代碼有什么問題? 謝謝。
我懷疑您的循環終止是錯誤的。
除了檢查node != NULL
,還應該檢查!q.empty()
。
同樣,調用q.front
不會從隊列中刪除該元素。 為此,您需要pop
(在調用front
)。
該代碼對我有用:
void printLevel(struct node* node){
std::queue<struct node*> q;
q.push(node);
while(!q.empty()) {
node=q.front();
q.pop();
if ( node != NULL ) {
std::cout << node->data << " ";
q.push(node->left);
q.push(node->right);
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.