请在此程序中建议级别树遍历的错误

时间:2017-02-14 21:57:26

标签: c++ tree

请在此程序中建议级别树遍历的错误 我得到一个无限循环所有打印1

算法:

对于每个节点,首先访问该节点,然后将其子节点放入FIFO队列。

printLevelorder(树)

struct A : std::enable_shared_from_this<A> 
{
    std::thread* t = nullptr;
    A() {}
    ~A(){ 
        t->join(); 
        delete t; 
    }
    void f() { 
        try{
            auto p = this->shared_from_this(); 
            std::cout << "p:" << p.get() << "\n";
        } catch(...) { 
            std::cout << "Exception !!!\n"; 
        }
    }
    void start() { 
        t = new std::thread(&A::f,this); 
    }
};
std::shared_ptr<A> create() { 
    A* a = new A();
    std::shared_ptr<A> p(a);
    p->start();
    return p;
}
int main()
{   
    int i = 0;
    std::map<int,std::shared_ptr<A>> map;
    while( i < 1024) { 
        auto ptr = create();
        map[i++] = ptr;
    } 
    return 0;
}

这是树的节点

1.Create an empty queue q
2.temp_node = root /*start from root*/
3.Loop while temp_node is not 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


#include<iostream>

这是用于保存树节点的队列的节点

struct node
{
struct node *left;
int data;
struct node *right;
};

1 个答案:

答案 0 :(得分:0)

在你的while循环中:

while (temp != NULL)
    {
    printf( "%d\t", root->data );
    if (temp->left)
        enQueue( frontandrear, root->left );
    if (temp->right)
        enQueue( frontandrear, root->right );
    temp = deQueue( frontandrear );
    }
}

enQueue的第二个参数中,您使用root,我认为您打算使用temp