(剑指Offer)面试题60:把二叉树打印成多行

题目:

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

思路:

很明显,采用广度优先遍历来解决,但因为需要按行输出,所以需要判断每一层的开始和结束,因此需要两个变量,一个表示当前层尚未打印的结点数,一个表示下一层结点的数目。

在线测试:

http://www.nowcoder.com/books/coding-interviews/445c44d982d04483b04a54f298796288?rp=3

AC代码:

/*
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*> nodes;
            nodes.push(pRoot);
            int curLevel=1;
            int nextLevel=0;

            TreeNode* tmp;
            vector<int> tLevel;
            while(!nodes.empty()){
                tmp=nodes.front();
                tLevel.push_back(tmp->val);

                if(tmp->left!=NULL){
                    nodes.push(tmp->left);
                    nextLevel++;
                }

                if(tmp->right!=NULL){
                    nodes.push(tmp->right);
                    nextLevel++;
                }

                nodes.pop();
                curLevel--;
                if(curLevel==0){
                    result.push_back(tLevel);
                    tLevel.clear();
                    curLevel=nextLevel;
                    nextLevel=0;
                }

            }

            return result;
        }

};

  

    原文作者:AndyJee
    原文地址: https://www.cnblogs.com/AndyJee/p/4719268.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞