二叉树层次遍历

#include 
#include 

using namespace std;

struct TreeNode
{
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode ( int x ) : val(x), left(nullptr), right(nullptr) {}
};

void BFS_print(TreeNode* root)
{
    queue< TreeNode* > Q;
    Q.push( root );

    while ( !Q.empty() )
    {
        // 处理队列首部元素
        TreeNode* node = Q.front();
        cout << node->val << endl;

        // 处理完首部元素后,将其弹出
        Q.pop();
        if ( node->left )
            Q.push( node->left );
        if ( node->right )
            Q.push( node->right );
    }
}

int main()
{
    TreeNode a(1);
    TreeNode b(2);
    TreeNode c(5);
    TreeNode d(3);
    TreeNode e(4);
    TreeNode f(6);

    a.left = &b;
    a.right = &c;
    b.left = &d;
    b.right = &e;
    c.right = &f;

    BFS_print(&a);

    return 0;
}

你可能感兴趣的:(二叉树层次遍历)