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] ]
思路:层序遍历,利用队列,一次性输出一层的所有节点,如果是偶数层,就将这一层输出的数组反转。
-
/** * 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 { private: vector<vector<int>> result; public: vector<vector<int>> zigzagLevelOrder(TreeNode* root) { if(!root) return result; queue<TreeNode *> q; q.push(root); int dep=1; while(!q.empty()){ int size=q.size(); vector<int> level; for(int i=0;i<size;i++){ TreeNode * node=q.front(); q.pop(); level.push_back(node->val); if(node->left) q.push(node->left); if(node->right) q.push(node->right); } if(dep%2==0) reverse(level.begin(),level.end()); dep++; result.push_back(level); } return result; } };