广度优先遍历:使用队列
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
#include
class Solution {
public:
vector> levelOrder(TreeNode* root)
{
vector> vv;
queue qu;
if(root != nullptr)
{
qu.push(root);
}
while(!qu.empty())
{
vector v;
TreeNode* ptr = nullptr;
int num = qu.size();
for(int i=0; ival);
qu.pop();
if(ptr->left != nullptr) { qu.push(ptr->left); }
if(ptr->right != nullptr) { qu.push(ptr->right); }
}
vv.push_back(v);
}
return vv;
}
};