103 Binary Tree Zigzag Level Order Traversal

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

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
        vector<vector<int>> res;
        if ( root == NULL ) return res;
        stack<TreeNode*> s1, s2;
        s1.push(root);
        int tag_left = true;
        while ( ! s1.empty() ) {
            vector<int> tmp;
            while ( ! s1.empty() ) {
                TreeNode *tnode = s1.top();
                s1.pop();
                tmp.push_back(tnode->val);
                if ( tag_left ) {
                    if ( tnode->left != NULL ) s2.push(tnode->left);
                    if ( tnode->right != NULL ) s2.push(tnode->right);
                }
                else {
                    if ( tnode->right != NULL ) s2.push(tnode->right);
                    if ( tnode->left != NULL ) s2.push(tnode->left);
                }
            }
            res.push_back(tmp);
            swap(s1, s2);
            tag_left = ( not tag_left );
        }
        return res;
    }
};

Notes
Note the usage of swap:

swap(s1, s2)
// or
s1.swap(s2)

results matching ""

    No results matching ""