LeetCode 102. Binary Tree Level Order Traversal
Solution1:
参考自《剑指offer》上的资料:https://blog.csdn.net/allenlzcoder/article/details/79785180
/**
* 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;
vector<int> temp;
queue<TreeNode* > my_que; //队列用来暂时存储二叉树节点
my_que.push(root);
int cur = 1, next = 0;
while (!my_que.empty()) {
temp.push_back(my_que.front()->val);
cur--;
if (my_que.front()->left) {
my_que.push(my_que.front()->left);
next++;
}
if (my_que.front()->right) {
my_que.push(my_que.front()->right);
next++;
}
my_que.pop();
if (cur == 0) {
res.push_back(temp);
temp.clear();
cur = next;
next = 0;
}
}
return res;
}
};