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]
]
/**
* 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>> zigzagLevelOrder(TreeNode* root) {
vector<vector<int>> result;
if(root==NULL)
return result;
TreeNode *p=root;
queue<TreeNode*> que1,que2;
que1.push(p);
while(que1.size()!=0 || que2.size()!=0){
vector<int> odd,even;
while(que1.size()){
TreeNode *tmp=que1.front();
que1.pop();
odd.push_back(tmp->val);
if(tmp->left) que2.push(tmp->left);
if(tmp->right) que2.push(tmp->right);
}
if(odd.size()) result.push_back(odd);
while(que2.size()){
TreeNode *tmp=que2.front();
que2.pop();
even.push_back(tmp->val);
if(tmp->left) que1.push(tmp->left);
if(tmp->right) que1.push(tmp->right);
}
if(even.size()){
reverse(even.begin(),even.end());
result.push_back(even);
}
}
return result;
}
};
//测试代码
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
TreeNode* initBTree(vector<int> input)
{
int size=input.size();
// cout<<"input.size:"<<size<<endl;
if (size < 1)
{
return NULL;
}
//动态申请size大小的指针数组
TreeNode **nodes = new TreeNode*[size];
//将int数据转换为TreeNode节点
for (int i = 0; i < size; i++)
{
if (input[i] == 0)
{
nodes[i] = NULL;
}
else
{
nodes[i] = new TreeNode(input[i]);
}
}
queue<TreeNode*> nodeQueue;
nodeQueue.push(nodes[0]);
TreeNode *node;
int index =1;
while (index < size )
{
node = nodeQueue.front();
nodeQueue.pop();
//handle left son
if(nodes[index]){
nodeQueue.push(nodes[index]);
node->left=nodes[index];
}
index++;
//handle right son
if(index<size && nodes[index]){
nodeQueue.push(nodes[index]);
node->right=nodes[index];
}
index++;
}
return nodes[0];
}
int main()
{
vector<int> input={};//3,9,20,0,0,15,7
vector<int> inResult;
TreeNode *root=initBTree(input);
// inOrder(root);
vector<vector<int>> result=zigzagLevelOrder(root);
for(int i=0;i<result.size();i++){
for(int j=0;j<result[i].size();j++){
cout<<result[i][j]<<" ";
}
cout<<endl;
}
return 0;
}