/** * 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>> levelOrder(TreeNode* root) { vector<vector<int> > res; if(!root) return res; deque<TreeNode*> Q; Q.push_back(root); bool flag = true; while(!Q.empty()) { int n = Q.size(); vector<int> layer; TreeNode* t; while(n) { if(flag) { t = Q.back(); Q.pop_back(); if(t->left) Q.push_front(t->left); if(t->right) Q.push_front(t->right); } else { t = Q.front(); Q.pop_front(); if(t->right) Q.push_back(t->right); if(t->left) Q.push_back(t->left); } layer.push_back(t->val); n--; } flag = !flag; res.push_back(layer); } return res; } };
利用双端队列实现偶数层的逆序。