难度4,出现频率3
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 7return its zigzag level order traversal as:
[ [3], [20,9], [15,7]
]
思路: 跟level order traversal一致,只是多一个flag记录每层正向还是逆向。
- vector<vector<int>> zigzagLevelOrder(TreeNode *root){
- vector<vector<int>> res;
- if(!root) return res;
- vector<int> level;
- queue<TreeNode *> myque;
- bool flag = true;
- TreeNode *last = root;
- myque.push(root);
- //main loop
- while(!myque.empty()){
- root = myque.front();
- myque.pop();
- if(root->left) myque.push(root->left);
- if(root->right) myque.push(root->right);
- if(flag == true)level.push_back(root->val);
- else level.insert(level.begin(), root->val);
- //when current level ends, store level in result, reset flag and level variable.
- if(root == last){
- res.push_back(level);
- level.clear();
- last = myque.back();
- flag = !flag;
- }
- }
- return res;
- }
No comments:
Post a Comment