Title: Zigzag print binary tree
Difficulty: Hard
Ideas: 1. A variable height is needed to indicate the printing direction (left to right or right to left) 2. A variable numOfChild is used to indicate how many nodes there are in this layer
Code: Implemented using a deque
class Solution {
public :
vector <vector <int > > zigzagLevelOrder(TreeNode* root) {
vector <vector <int > > ivec;
if (root == NULL) {
return ivec;
}
deque <TreeNode *> deq;
deq.push_back(root);
int height = 0 ;
int numOfChild = 1 ;
while (!deq.empty()) {
vector <int > vec;
for (int i = 0 ; i < numOfChild; i++) {
TreeNode *node;
if (height%2 == 0 ){
node = deq.back();
deq.pop_back();
if (node->left != NULL){
deq.push_front(node->left);
}
if (node->right != NULL){
deq.push_front(node->right);
}
}else {
node = deq.front();
deq.pop_front();
if (node->right != NULL){
deq.push_back(node->right);
}
if (node->left != NULL){
deq.push_back(node->left);
}
}
vec.push_back(node->val);
}
height++;
numOfChild = deq.size();
ivec.push_back(vec);
}
return ivec;
}
};