方法一:(迭代)
/**
* 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>> v;
if(root == NULL) return v; queue<TreeNode *> q;
q.push(root); TreeNode *curNode = NULL;
vector<int> a;
while(!q.empty())
{
int len = q.size();
for(size_t i = ; i < len; i++)
{
curNode = q.front(); q.pop();
a.push_back(curNode->val);
if(curNode->left != NULL) q.push(curNode->left);
if(curNode->right != NULL) q.push(curNode->right);
}
v.push_back(a);
a.clear();
} return v;
}
};
方法二:(递归)
class Solution
{
public:
vector<vector<int>> levelOrder(TreeNode* root)
{
vector<vector<int>> v;
levelOrderHelp(root, , v);
return v;
} void levelOrderHelp(TreeNode *root, int level, vector<vector<int>>& v)
{
if(root == NULL) return; // 注意
if(level >= v.size()) v.push_back(vector<int>()); v[level].push_back(root->val);
levelOrderHelp(root->left, level + , v);
levelOrderHelp(root->right, level + , v);
}
};