zoukankan      html  css  js  c++  java
  • 剑指 Offer 32

    1. 将根节点插入队列中;
    2. 创建一个新队列,用来按顺序保存下一层的所有子节点;
    3. 对于当前队列中的所有节点,按顺序依次将儿子插入新队列;
    4. 按从左到右、从右到左的顺序交替保存队列中节点的值;
    5. 重复步骤2-4,直到队列为空为止。
    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        vector<vector<int>> levelOrder(TreeNode* root) {
            if (!root) return {};
            vector<vector<int>> res;
            queue<TreeNode*> q;
            q.push(root);
    
            bool flag = false;
            while (q.size()) {
                int cnt = q.size();
                vector<int> level(cnt);
                for (int i = 0; i < cnt; i++) {
                    TreeNode* t = q.front();
                    q.pop();
    
                    level[i] = t->val;
    
                    if (t->left) q.push(t->left);
                    if (t->right) q.push(t->right);
                }
                if (flag) reverse(level.begin(), level.end());
                res.push_back(level);
                flag = !flag;
            }
    
            return res;
        }
    };
    
  • 相关阅读:
    基于jenkins+gitlab的自动集成环境的搭建
    函数指针与委托
    详解C#break ,continue, return (转)
    REST 与 web service 的比较
    Python
    python
    python
    python
    python 1.0
    python 0.0
  • 原文地址:https://www.cnblogs.com/fxh0707/p/15053843.html
Copyright © 2011-2022 走看看