103. Binary Tree Zigzag Level Order Traversal (Medium)

Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).

For example: Given binary tree[3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

return its zigzag level order traversal as:

[
  [3],
  [20,9],
  [15,7]
]

Solution 1: stack

vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
    vector<vector<int>> res;
    if (!root) return res;
    stack<TreeNode*> s, s2; // s: current level, s2: next level
    s.push(root);
    bool left = false;
    while (!s.empty()) {
        // one level
        vector<int> level(s.size());
        int i = 0;
        if (left) {
            // from left to right
            // push right then left;
            left = false;
            while (!s.empty()) {
                TreeNode* top = s.top(); s.pop();
                level[i++] = top->val;
                if (top->right) s2.push(top->right);
                if (top->left) s2.push(top->left);
            }
        } else {
            // from right to left
            // push left then right
            left = true;
            while (!s.empty()) {
                TreeNode* top = s.top(); s.pop();
                level[i++] = top->val;
                if (top->left) s2.push(top->left);
                if (top->right) s2.push(top->right);
            }
        }
        swap(s,s2);
        res.push_back(level);
    }

    return res;
}

Solution2: BFS

vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
    vector<vector<int>> res;
    queue<TreeNode*> q;
    if (root) q.push(root);
    bool left = true;
    while(!q.empty()) {
        // one level
        int size = q.size();
        vector<int> level(size);
        for (int i = 0; i < size; ++i) {
            TreeNode* top = q.front(); q.pop();
            level[i] = top->val;
            if (top->left) q.push(top->left);
            if (top->right) q.push(top->right);

        }
        if (!left) reverse(level.begin(), level.end());
        left = !left;
        res.push_back(level);
    }
    return res;
}

results matching ""

    No results matching ""