leetcode[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,#,#,15,7},

    3
   / 
  9  20
    /  
   15   7

return its zigzag level order traversal as:

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

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

/**
 * Definition for binary tree
 * 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;
        vector<int> tmp;
        stack<TreeNode *> Spre,Scurr;
        if(root==NULL)return res;
        else
        {
            int flag=0;
            Spre.push(root);
            while(1)
            {
                flag++;
                while(!Spre.empty())
                {
                  TreeNode *tem=Spre.top();
                  Spre.pop();
                  tmp.push_back(tem->val);
                  if(flag%2==1)
                  {
                     if(tem->left)Scurr.push(tem->left);
                     if(tem->right)Scurr.push(tem->right);                      
                  }
                  else
                  {
                     if(tem->right)Scurr.push(tem->right);
                     if(tem->left)Scurr.push(tem->left);                        
                  }
                }
                res.push_back(tmp);
                tmp.clear();
                if(Scurr.empty())break;
                else Scurr.swap(Spre);
            }
            return res;
        }        
    }
};
原文地址:https://www.cnblogs.com/Vae1990Silence/p/4281347.html