剑指offer——面试题61:按之字形打印二叉树

 题目:请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推

    代码:

[cpp]  view plain  copy
  1. /* 
  2. struct TreeNode { 
  3.     int val; 
  4.     struct TreeNode *left; 
  5.     struct TreeNode *right; 
  6.     TreeNode(int x) : 
  7.             val(x), left(NULL), right(NULL) { 
  8.     } 
  9. }; 
  10. */  
  11. class Solution {  
  12. public:  
  13.     vector<vector<int> > Print(TreeNode* pRoot) {  
  14.         vector<vector<int>> vreturn;  // 专门用来返回  
  15.         if(pRoot == NULL)  
  16.             return vreturn;  
  17.           
  18.         vector<int> vline;  // 存储每一行的结点  
  19.         vector<vector<int>> v;  
  20.           
  21.         stack<TreeNode*> level[2];  // 定义两个栈,一个存储奇数行,一个存储偶数行  
  22.         int current = 0;  
  23.         int next = 1;  
  24.           
  25.         level[current].push(pRoot);    
  26.         while(!level[0].empty() || !level[1].empty())  
  27.         {  
  28.             TreeNode* pNode = level[current].top();  
  29.             level[current].pop();  
  30.             vline.push_back(pNode->val);  
  31.               
  32.             if(current == 0)  // 如果当前行是奇数,先把下一行的左结点压入栈,,因为左结点后弹出  
  33.             {  
  34.                 if(pNode->left != NULL)     
  35.                 {  
  36.                     level[next].push(pNode->left);  
  37.                 }  
  38.                 if(pNode->right != NULL)  
  39.                 {  
  40.                     level[next].push(pNode->right);  
  41.                 }  
  42.             }  
  43.             else     // 如果当前行是偶数,先把下一行中的右结点压入栈,,因为右结点后弹出  
  44.             {  
  45.                 if(pNode->right != NULL)  
  46.                 {  
  47.                     level[next].push(pNode->right);  
  48.                 }  
  49.                 if(pNode->left != NULL)  
  50.                 {  
  51.                     level[next].push(pNode->left);  
  52.                 }  
  53.             }  
  54.               
  55.             if(level[current].empty())  
  56.             {  
  57.                 v.push_back(vline);  
  58.                 vline.clear();  // 每次都要把 vline 那一行清除,以便存储下一行的数据  
  59.                 current = 1-current;  
  60.                 next = 1-next;  
  61.             }  
  62.               
  63.         }  
  64.         return v;  
  65.     }  
  66.       
  67. };  

    分析:按照之字形打印二叉树,奇数行按照从左到右的顺序打印,偶数行按照从右往左的顺序打印。这样,定义两个栈即可,分别存储奇数行和偶数行


  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值