《剑指offer》面试题60——把二叉树打印成多行(C++)

题目:从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。

vector<vector<int> > Print(TreeNode* pRoot)
{
    vector<vector<int> >  vec;
    if(pRoot==NULL)
        return vec;
    queue <TreeNode*> q;
    q.push(pRoot);
    while(!q.empty())
    {
            int ToBeprint = q.size();
            vector <int> tmp;
            while(ToBeprint--)
            {
               TreeNode * node=q.front();
                tmp.push_back(q.front()->val);

                if(node->left!=NULL)  q.push(node->left);
                if(node->right!=NULL)  q.push(node->right);
                q.pop();

            }
            vec.push_back(tmp);
    }
    return vec;
}

运行结果为:

10
5  12
4  7


Process returned 0 (0x0)   execution time : 0.263 s
Press any key to continue.

猜你喜欢

转载自blog.csdn.net/zhenaoxi1077/article/details/80432110