103. Binary Tree Zigzag Level Order Traversal

题目链接

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

代码

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

        vector 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 Order Traversal)