题解 | 按之字形顺序打印二叉树 还可以再优化 比如if语句里可以只有num的逻辑

按之字形顺序打印二叉树

https://www.nowcoder.com/practice/91b69814117f4e8097390d107d2efbe0

/**
 * struct TreeNode {
 *	int val;
 *	struct TreeNode *left;
 *	struct TreeNode *right;
 *	TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 * };
 */
#include <queue>
#include <vector>
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param pRoot TreeNode类 
     * @return int整型vector<vector<>>
     */
    vector<vector<int> > Print(TreeNode* pRoot) {
        // write code here
        //设置一个变量记录这是第几层
        vector<vector<int>> num;
        if(pRoot==nullptr)return num;
        queue<TreeNode*> read;
        read.push(pRoot);
        int level=1;
        while(!read.empty()){
            vector<int> a;
            int i=0;
            int x=read.size();
            if(level%2==1){
                while(i<x){
                    TreeNode* cur=read.front();
                    read.pop();
                    a.push_back(cur->val);
                    if(cur->left)read.push(cur->left);
                    if(cur->right)read.push(cur->right);
                    i++;
                }
                
            }
            else {
                while(i<x){
                    TreeNode* cur=read.front();
                    read.pop();
                    //a.push_back(cur->val);
                    a.insert(a.begin(), cur->val);
                    if(cur->left)read.push(cur->left);
                    if(cur->right)read.push(cur->right);
                    i++;
                }
            //这段逻辑有误 可能需要双端队列
            //nono 不需要双端队列也可以,因为主要是在输出的数组中可以做操作可以顺序建立队列灾写入数组的时候从头开始插入元素就可以达到倒序。 
            //使用栈。
            }
            num.push_back(a);
            level++;
            
        }
        return num; 
    }
};

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务