Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).
For example:
Given binary tree {3,9,20,#,#,15,7}
,
3 / \ 9 20 / \ 15 7
return its zigzag level order traversal as:
[ [3], [20,9], [15,7] ]
标准BFS,层序遍历。
/** * 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>> res; vector<int> traversal; int level = 0; queue<TreeNode*> que; if(root==NULL) return res; que.push(root); while(!que.empty()){ int len = que.size(); traversal.clear(); for(int i=0; i<len; ++i){//BFS搜索每次把一整层的内容出队列 TreeNode* FNode = que.front(); traversal.push_back(FNode->val); if(FNode->left) que.push(FNode->left); if(FNode->right) que.push(FNode->right); que.pop(); } if(level%2==0){ res.push_back(traversal); } if(level%2==1){ res.push_back(vector<int>(traversal.rbegin(),traversal.rend()));//翻转vector数组 } level++; } return res; } };