首页 > 代码库 > Binary Tree Zigzag Level Order Traversal

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]]
代码:
 1 class Solution { 2 public: 3     vector<vector<int> > zigzagLevelOrder(TreeNode *root) { 4         vector<vector<int>> res; 5         if(!root) return res; 6         vector<TreeNode *> prev; 7         vector<TreeNode *> cur; 8         cur.push_back(root); 9         bool even = true;10         while(!cur.empty()){11             vector<int> lev_res;12             if(even){13                 for(vector<TreeNode *>::iterator it = cur.begin(); it != cur.end(); it++)14                     lev_res.push_back((*it)->val);15             }else{16                 for(vector<TreeNode *>::reverse_iterator rit = cur.rbegin(); rit != cur.rend(); rit++)17                     lev_res.push_back((*rit)->val);18             }19             res.push_back(lev_res);20             even ^= true;21             prev = cur;22             cur.clear();23             for(auto i: prev){24                 if(i->left) cur.push_back(i->left);25                 if(i->right) cur.push_back(i->right);26             }27         }28         return res;29     }30 };