數據結構-劍指offer-把二叉樹打印成多行

題目:從上到下按層打印二叉樹,同一層結點從左至右輸出。每一層輸出一行。

因爲要按層打印,首先想到的是層次遍歷。在二叉樹的深度這道題中,首先應用到了層次遍歷。每一層的節點值存入一個小vector c,再把小vector c存到大vector vec中,打印vec。(題目沒有要求換行,所以不需要考慮換行符)

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()){
                int depth = 0;
                int len = que.size();
                vector<int> c;
                while(depth<len){
                    depth++;
                    TreeNode* node = que.front();
                    que.pop();
                    c.push_back(node->val);
                    if(node->left)
                        que.push(node->left);
                    if(node->right)
                        que.push(node->right); 
                }
                vec.push_back(c);
            }
            return vec;
        }
};

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章