鋸齒形層次遍歷,思路與二叉樹的層次遍歷相同,稍微作點改動,區別在於此處使用的是雙端隊列,分別從前到後和從後到前地遍歷二叉樹。代碼以下css
vector<vector<int>> zigzagLevelOrder(TreeNode* root) { deque<TreeNode*>q; vector<vector<int>>res; if (root==NULL)return res; else{ q.push_back(root); bool dir=true;//標誌位,指示從前日後仍是從後往前遍歷層級 while(!q.empty()) { int n=q.size(); vector<int>r; for(int i=0;i<n;i++) { if(dir)//注意遍歷的方式和左右結點的插入位置 { TreeNode *cur=q.front(); q.pop_front(); r.push_back(cur->val); if(cur->left!=NULL) q.push_back(cur->left); if(cur->right!=NULL) q.push_back(cur->right); } else{ TreeNode *cur=q.back(); q.pop_back(); r.push_back(cur->val); if(cur->right!=NULL) q.push_front(cur->right); if(cur->left!=NULL) q.push_front(cur->left); } } res.push_back(r); dir=!dir;//遍歷一層後反過來遍歷 } } return res; }