美文网首页
103. Binary Tree Zigzag Level Or

103. Binary Tree Zigzag Level Or

作者: jecyhw | 来源:发表于2019-06-12 06:10 被阅读0次

题目链接

https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/

代码

class Solution {
public:
    vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
        vector<vector<int>> ans;
        if (root == NULL) {
            return ans;
        }
        queue<TreeNode*> que;
        que.push(root);
        que.push(NULL);

        vector<int> ve;
        TreeNode *t;
        while (true) {
            t = que.front();
            que.pop();
            if (t == NULL) {
                ans.push_back(ve);
                ve.clear();
                if (que.empty()) {
                    break;
                } else {
                    que.push(NULL);
                }
            } else {
                if (t->left != NULL) {
                    que.push(t->left);
                }
                if (t->right != NULL) {
                    que.push(t->right);
                }
                ve.push_back(t->val);
            }
        }

        for (int i = 1; i < ans.size(); i += 2) {
            for (int j = 0, k = ans[i].size() - 1; j < k; ++j, --k) {
                swap(ans[i][j], ans[i][k]);
            }
        }
        return ans;
    }
};

相关文章

网友评论

      本文标题:103. Binary Tree Zigzag Level Or

      本文链接:https://www.haomeiwen.com/subject/loihfctx.html