:分层打印二叉树

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




/*
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};
*/
class Solution {
public:
        vector<vector<int> > Print(TreeNode* pRoot)  //二维向量
        {
            vector<vector<int> > vec;
            if (pRoot==NULL)
                return vec;
            queue<TreeNode*> que;
            que.push(pRoot);
            while(!que.empty())
            {   vector<int> c;
                int m=que.size();   
                for(int i=0;i<m;i++)     //这里不能直接用i<que.size(),因为for循环每一次的size都会变。

                {
                    TreeNode* t=que.front();
                    que.pop();
                    c.push_back(t->val);
                    if(t->left)
                    que.push(t->left);
                    if(t->right)
                    que.push(t->right);
                }
             vec.push_back(c);
            }
            return vec;
        }
    
};

 测试时: 8 

            6    10

        5    7    9   11

输出:<<8><6 10><5 7 9 11>>

猜你喜欢

转载自blog.csdn.net/qq_42209189/article/details/80803637