/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
* 奇数的时候a出对,b入队
*/
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> ans;
if (root == NULL)
return ans;
int cnt = 1;
queue<TreeNode*> a[2];
a[1].push(root);
while (a[0].size() || a[1].size())
{
vector<int> tmp;
while (a[cnt].size())
{
root = a[cnt].front();
a[cnt].pop();
if (root->left)
a[(cnt + 1) % 2].push(root->left);
if (root->right)
a[(cnt + 1) % 2].push(root->right);
tmp.push_back(root->val);
}
cnt = (cnt + 1) % 2;
ans.push_back(tmp);
}
return ans;
}
};
level遍历102. Binary Tree Level Order Traversal
最新推荐文章于 2022-06-28 23:47:12 发布