为什么我的printLevel功能不起作用?

时间:2013-10-10 14:11:56

标签: c++ stl tree queue

我已编写此代码来执行二进制搜索树的级别顺序遍历。错误仅在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(树)

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)。我的代码出了什么问题?感谢。

1 个答案:

答案 0 :(得分:1)

我怀疑你的循环终止是错误的。

您应该检查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);
            }
    }
}