您的位置:首页 > 其它

【刷题之路】二叉树按层打印

2016-05-30 21:05 246 查看
按层打印,换层换行

class TreePrinter {

public:

    vector<vector<int> > printTree(TreeNode* root) {

        // write code here

        TreeNode* last;

        TreeNode* nlast;

        vector<int> temp; //用于保存每一层的值

        queue<TreeNode*> tmp; //用于保存遍历的树节点

        vector<vector<int> > res;

        last=root;

        nlast=root;

        tmp.push(root);

        while(!tmp.empty()){

            last=tmp.front(); //last为队列的头,即为遍历的节点

            tmp.pop();

            temp.push_back(last->val);

            if(last->left) tmp.push(last->left); //将当前遍历的节点的左右子节点放入队列中

            if(last->right) tmp.push(last->right);   

            if(last==nlast){

                nlast=tmp.back(); //当last==nlast,下一层的所有节点必然已经全部放入队列中,于是让nlast=tmp的末尾,即为下一行的最后一个节点

                res.push_back(temp);

                temp.clear();

            }     

        }

        return res;

    }

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  刷题 算法 二叉树