剑指offer 面试题. 按之字形顺序打印二叉树
题目描述
请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。
方法1:
正常层次遍历,利用普通队列。逢奇数行(从0算起)就把该层结果逆序。
1 class Solution { 2 public: 3 vector<vector<int> > Print(TreeNode* pRoot) { 4 if(pRoot==nullptr){return {};} 5 queue<TreeNode*> my_queue; 6 my_queue.push(pRoot); 7 vector<vector<int>>res; 8 vector<int> vec; 9 int cnt=0; 10 while(not my_queue.empty()){ 11 vec.clear(); 12 int cur_siz=my_queue.size(); 13 for(int i=0;i<cur_siz;++i){ 14 auto cur=my_queue.front(); 15 my_queue.pop(); 16 vec.push_back(cur->val); 17 if(cur->left){ 18 my_queue.push(cur->left); 19 } 20 if(cur->right){ 21 my_queue.push(cur->right); 22 } 23 } 24 if(cnt&1){ 25 reverse(vec.begin(),vec.end()); 26 } 27 res.push_back(vec); 28 ++cnt; 29 } 30 return res; 31 } 32 };
方法2:
利用双端队列,队列中顺序始终是正常的,但奇数行从右向左遍历,pop右边的,孩子push进左边。偶数行从左向右遍历,pop左边的,孩子push进右边。
1 class Solution { 2 public: 3 vector<vector<int> > Print(TreeNode* pRoot) { 4 if(pRoot==nullptr){return {};} 5 deque<TreeNode*> my_queue; 6 my_queue.push_back(pRoot); 7 vector<vector<int>>res; 8 int cnt=0; 9 while(not my_queue.empty()){ 10 res.push_back({}); 11 int cur_siz=my_queue.size(); 12 decltype(pRoot) cur; 13 for(int i=0;i<cur_siz;++i){ 14 if(cnt&1){ 15 cur=my_queue.back(); 16 my_queue.pop_back(); 17 if(cur->right){ 18 my_queue.push_front(cur->right); 19 } 20 if(cur->left){ 21 my_queue.push_front(cur->left); 22 } 23 } 24 else{ 25 cur=my_queue.front(); 26 my_queue.pop_front(); 27 if(cur->left){ 28 my_queue.push_back(cur->left); 29 } 30 if(cur->right){ 31 my_queue.push_back(cur->right); 32 } 33 } 34 res.back().push_back(cur->val); 35 } 36 ++cnt; 37 } 38 return res; 39 } 40 };
进击的小🐴农