刷題之二叉樹打印

是這樣的,最近在刷題,多次遇到二叉樹打印,如按層打印和之字形打印;

其實這類問題可以統一用一類方法解決  -- BFS

/*
之字形打印二叉樹 
*/

/*
    思路就是使用一個隊列保存節點,然後按照每一層節點的數量加一個flag判斷 設置 反轉
*/
class Solution {
public:
    vector<vector<int> > Print(TreeNode* pRoot) {
        vector<vector<int>> res;
        queue<TreeNode*> Q;
        if(!pRoot) return res;
        Q.push(pRoot);
        bool flag = true;
        while(!Q.empty()){
            int len = Q.size();
            vector<int> tmp(len, -1);
            for(int i = 0; i < len; ++i){
                 TreeNode *p = Q.front();
                Q.pop();
                if(p->left) Q.push(p->left);
                if(p->right) Q.push(p->right);
                int index = flag ? i : len - 1 - i;
                tmp[index] = p->val;
            }
            flag = !flag;
            res.push_back(tmp);
        }
        return res;
    }
     
};
按層順序打印二叉樹

class Solution {
public:
    vector<vector<int> > Print(TreeNode* pRoot) {
        vector<vector<int>> res;
        queue<TreeNode*> Q;
        if(!pRoot) return res;
        Q.push(pRoot);
      
        while(!Q.empty()){
            int len = Q.size();
            vector<int> tmp(len, -1);
            for(int i = 0; i < len; ++i){
                 TreeNode *p = Q.front();
                Q.pop();
                if(p->left) Q.push(p->left);
                if(p->right) Q.push(p->right);
               
                tmp[i] = p->val;
            }
           
            res.push_back(tmp);
        }
        return res;
    }
     
};

 

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