【劍指Offer】面試題60:把二叉樹打印成多行

整理自劍指Offer


一:題目描述


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


二:解題思路


層次遍歷二叉樹,用隊列保存將要打印的結點

需要用到兩個變量:

1.表示當前層中還沒有打印的結點的數

2.表示下一層節點的數目


三:代碼實現



非遞歸實現

/*
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> > result;
            if(pRoot==NULL)
                return result;
            
            queue<TreeNode*> q;
            q.push(pRoot);
            
            int printNodeSum=1;
            int nextNodeSum=0;
            vector<int> rowNode;
            while(!q.empty()){
                
                //獲取隊首元素
                TreeNode* pCurrentNode=q.front();
                //保存當前節點
                rowNode.push_back(pCurrentNode->val);
                
                if(pCurrentNode->left){
                     q.push(pCurrentNode->left);
                     nextNodeSum++;
                }
                if(pCurrentNode->right){
                    q.push(pCurrentNode->right);
                    nextNodeSum++;
                }
                
                //出隊
                q.pop();
                printNodeSum--;
                
                //如果當前行打印結束
                if(printNodeSum==0){
                    result.push_back(rowNode);
                    rowNode.clear();
                    printNodeSum=nextNodeSum;
                    nextNodeSum=0;
                }//if
                   
            }//while
            
            return result;
        }
    
};

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