劍指offer:按照層的方式打印二叉數C++

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

 

/*
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};
*/
// 1.按照層打印二叉樹,需要使用隊列,先進先出
// 2.每層打印一行,需要判斷當前行有多少個節點,然後打印換行
class Solution {
public:
        vector<vector<int> > Print(TreeNode* pRoot) {
        //首先將二叉樹存入到隊列中
            vector<vector<int>> t;
            queue<TreeNode*> que;
            if(pRoot==NULL) return t;
            que.push(pRoot);
            int next = 0;
            int current = 1;
            while(!que.empty()) {
                vector<int> node;
                while(current != 0 && !que.empty()){ //對當前層進行存儲,並統計下一層的個數
                    TreeNode* top = que.front();
                    node.push_back(top->val);
                    current--;
                    que.pop();
                    if(top->left!=NULL) {
                        que.push(top->left);
                        next++;
                    }
                    if(top->right!=NULL) {
                        que.push(top->right);
                        next++;
                    }
                }
                t.push_back(node);
                current = next;
                next = 0;
            }
            return t;
        }
    
};

 

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