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

按之字形顺序打印二叉树

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;
        vector<TreeNode*> t;
        if (pRoot)t.push_back(pRoot);
        bool flag = true;//是否该反向
        while (!t.empty()) {
            auto t1 = new vector<TreeNode*>();
            auto r = new vector<int>();//保存当前行
            for (int i = 0; i < t.size(); i++) {
                TreeNode*f = t[t.size()-1-i]; //反向读取
                if (flag? f->left:f->right)t1->push_back(flag? f->left:f->right);
                if (!flag? f->left:f->right)t1->push_back(!flag? f->left:f->right);
                r->push_back(f->val);
            }
            res.push_back(*r);
            t = *t1;
            flag = !flag;
        }
        return res;
    }
};

全部评论

相关推荐

阿里巴巴各部门年终奖开奖了,有人拿到了220w
真烦好烦真烦:拿命换钱呢,公司给你220万,肯定是因为你对公司的贡献大于220万,想想要多厉害多累才能达到
投递阿里巴巴集团等公司10个岗位 >
点赞 评论 收藏
分享
牛客10001:G了+1,被前端/客户端给捞起来了,不太想面
投递美团等公司10个岗位 美团求职进展汇总
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务