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,#,#,15,7},
3
/ \
9 20
/ \
15 7
return its level order traversal as:
[
[3],
[9,20],
[15,7]
]
confused what"{1,#,2,3}"means? > read more on how binary tree is serialized on OJ.
OJ's Binary Tree Serialization:
The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.
Here's an example:
1
/ \
2 3
/
4
\
5
For example:
Given binary tree{3,9,20,#,#,15,7},
3
/ \
9 20
/ \
15 7
return its level order traversal as:
[
[3],
[9,20],
[15,7]
]
confused what"{1,#,2,3}"means? > read more on how binary tree is serialized on OJ.
OJ's Binary Tree Serialization:
The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.
Here's an example:
1
/ \
2 3
/
4
\
5
The above binary tree is serialized as"{1,2,3,#,#,4,#,#,5}".
这个题目,的思路和2重复了 直接可用
只需要删去,翻转代码就行
queue<TreeNode*> node;
vector<vector<int> > vreturn;
bool flag = true;//0-left-right
int ceil_num = 0;
int ceil_numtmp = 0;
if(root != NULL )
{
ceil_num = 1;
node.push(root);
}
else
return vreturn;
while(!node.empty())
{
vector<int> numvector(ceil_num);
for(int i = 0;i < ceil_num;i++)
{
TreeNode *now = node.front();
numvector[i] = now->val;
node.pop();
if(now->left != NULL)
{
ceil_numtmp ++;
node.push(now->left);
}
if(now->right != NULL)
{
ceil_numtmp ++;
node.push(now->right);
}
}
flag = !flag;
if(flag == true)
{
//reverse
for(int i = 0;i < (ceil_num/2);i++)
{
int tmp = numvector[ceil_num -i - 1];
numvector[ceil_num -i - 1] = numvector[i];
numvector[i] = tmp;
}
}
vreturn.push_back(numvector);
ceil_num = ceil_numtmp;
ceil_numtmp = 0;
}
return vreturn;