/**
* 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:
void fun(TreeNode *root,vector<vector<int>> &ans,int num)//num表示第几层
{
if(root==NULL)return;
if(ans.size()<num)//没有num层 新建一个
{
vector<int> temp;
temp.push_back(root->val);
ans.push_back(temp);
}
else
{
ans[num-1].push_back(root->val);
}
fun(root->left,ans,num+1);
fun(root->right,ans,num+1);
}
vector<vector<int>> levelOrder(TreeNode* root)
{
vector<vector<int>> ans;
vector<int> v;
if(root==NULL)
{
return ans;
}
fun(root,ans,1);
return ans;
}
};
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
For example:
Given binary tree [3,9,20,null,null,15,7]
,
3 / \ 9 20 / \ 15 7
return its level order traversal as:
[ [3], [9,20], [15,7] ]
解法:先序遍历二叉树节点(保证每一层先访问左边结点),把每个结点的层数写出来,如果答案中有这一层,直接放进去,没有的话,新建一个放进去。
或者非递归的方法,用队列存储节点。方法参考http://www.cnblogs.com/grandyang/p/4051321.html