[leetcode]Binary Tree Level Order Traversal
#include <iostream> #include <vector> #include <stack> #include <queue> using namespace std; 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) { result.clear(); if (!root) return result; queue<TreeNode *> q;//层序遍历需要一个queue q.push(root); queue<TreeNode *> tmpQ;//因为每一层要分开,所以另开辟一个queue缓存一层 while(!q.empty()){ while(!q.empty()){ tmpQ.push(q.front()); q.pop(); } vector<int> oneLevel; while(!tmpQ.empty()){ oneLevel.push_back(tmpQ.front()->val);//对于该层全部遍历 if (tmpQ.front()->left) q.push(tmpQ.front()->left); if (tmpQ.front()->right) q.push(tmpQ.front()->right); tmpQ.pop(); } result.push_back(oneLevel); } return result; } private: vector<vector<int> > result;//!! }; int main() { return 0; }
EOF