• (剑指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;
            }
    
    };
    

      

  • 相关阅读:
    在 docker 容器中捕获信号
    python入门二维码生成
    SSH 端口转发
    Python之模块与包
    滑块验证demo示例
    上下界网络流初探
    大整数模板
    计算几何模板
    关于差分约束系统的脑洞
    并查集,以及可拆分并查集
  • 原文地址:https://www.cnblogs.com/AndyJee/p/4719268.html
Copyright © 2020-2023  润新知