zoukankan      html  css  js  c++  java
  • leetcode 103二叉树的锯齿形层次遍历

    与102相比就增加了flag,用以确定要不要进行reverse操作

    reverse:STL公共函数,对于一个有序容器的元素reverse ( s.begin(),s.end() )可以使得容器s的元素顺序反转;

    C++代码:

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    /**
    最直接的想法是利用层次遍历,然后reverse偶数层的数据
    
    **/
    class Solution {
    public:
        vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
            if(root==NULL) return {};
            vector<vector<int>> res;
            queue<TreeNode*> q;
            TreeNode* p;
            q.push(root);
            int flag=1;
            while(!q.empty()){
                int k=q.size();
                vector<int> level;
                for(int i=0;i<k;i++){
                    p=q.front();
                    q.pop();
                    level.push_back(p->val);
                    if(p->left) q.push(p->left);
                    if(p->right) q.push(p->right);
                }
                if(flag==0) reverse(level.begin(),level.end());
                flag=(flag+1)%2;
                res.push_back(level);
            }
            return res;
        }
    };

     相似:

    102 103 107

  • 相关阅读:
    acwing272. 最长公共上升子序列
    哈夫曼编码简单实现
    Linked List Sorting
    jmeter-线程组
    css-书写规范
    mysql-踩坑记录
    vue-npm install
    css-选择器
    js-process对象
    linux-常用命令
  • 原文地址:https://www.cnblogs.com/joelwang/p/10332372.html
Copyright © 2011-2022 走看看