题解 | #按之字形顺序打印二叉树#

按之字形顺序打印二叉树

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) {}
 * };
 */
class Solution {
  public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param pRoot TreeNode类
     * @return int整型vector<vector<>>
     */
    vector<vector<int> > Print(TreeNode* pRoot) {
        // write code here
        vector<vector<int>> res;
        if (pRoot == nullptr) return res;
        queue<TreeNode*> q;
        queue<TreeNode*> p;
        q.push(pRoot);
        bool falg=true;
        while (!q.empty()) {
            vector<int> cur1;
            int n = q.size();
            falg=!falg;//奇数行翻转,偶数行不翻转
            for (int i = 0; i < n; i++) {//为奇数行时
                TreeNode* now1 = q.front();
                q.pop();
                cur1.push_back(now1->val);
                if (now1->left)
                    q.push(now1->left);
                if (now1->right)
                    q.push(now1->right);
            }
            if(falg)//为偶数行时,翻转
            reverse(cur1.begin(),cur1.end());
            res.push_back(cur1);
        }
        return res;
    }
};

全部评论

相关推荐

03-31 14:46
已编辑
门头沟学院 Web前端
励志成为双港第一ja...:这其实很正常,离的太远了,他认为你不会来,就为了混个面试,而且成本很高,实习生都优先选本地高校。吃了地域的亏,所有很多时候地域可能比院校层次更重要。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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