• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 众包
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
kulukulu
博客园    首页    新随笔    联系   管理    订阅  订阅
leetcode 103

此题难度在于如何标记每一层的末尾节点。

思路1:队列层次遍历,遇到偶数层末尾反转一下数组

class Solution {         
public:
    vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
        vector<vector<int>> res;
        if(!root) return res;
        int t;
        vector<int> tmp;        
        deque<TreeNode*> deq;
        deq.push_back(root);
        TreeNode* p,*tail=root;//tail记录每一层的最后一个结点
        bool isEven=true;    //当前遍历到的层数是奇数层,就从左到右遍历
        while(!deq.empty()){
            p=deq.front();
            tmp.push_back(p->val);
            deq.pop_front();

            if(p->left)  deq.push_back(p->left);
            if(p->right)  deq.push_back(p->right);
            if(p==tail){                                //遍历完一层
                tail=deq.back();
                if(!isEven){                //交换vector位置
                    int l=tmp.size();
                    for(int i=0;i<l/2;i++){
                        t=tmp[l-1-i];
                        tmp[l-1-i]=tmp[i];
                        tmp[i]=t;
                    }
                }
                res.push_back(tmp);
                isEven=!isEven;
                tmp.clear();
            }
        }
        return res;
    }
};

思路2:双栈

class Solution {
public:
    vector<vector<int>> zigzagLevelOrder(TreeNode* root) {

        if(root ==NULL)return {};
        stack<TreeNode*> s;
        stack<TreeNode*> q;
        int flag = 0;//使用哪个栈
        vector<vector<int>> res;
        s.push(root);
        while(!s.empty() || !q.empty())
        {
            
           if(flag == 0)
           {
               vector<int> v_t;
               flag = 1;
               while(!s.empty())
               {
                   TreeNode* tmp = s.top();s.pop();
                   v_t.push_back(tmp->val);
                   if(tmp->left) q.push(tmp->left);
                   if(tmp->right) q.push(tmp->right);
                    
               }
               if(v_t.size()>0) res.push_back(v_t);
               
           }
           else
           {
               vector<int> v_t;
               flag = 0;
               while(!q.empty())
               {
                   TreeNode* tmp = q.top();q.pop();
                   v_t.push_back(tmp->val);
                   if(tmp->right) s.push(tmp->right);
                   if(tmp->left) s.push(tmp->left);
                    
               }
               if(v_t.size()>0) res.push_back(v_t);
           }
            
        }
        return res;

           
    }
};

 

posted on 2019-03-17 16:57  kulukulu  阅读(103)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3