zoukankan      html  css  js  c++  java
  • 102. 二叉树的层序遍历

    水题,只是为了练一下bfs标记层数

    dfs就行

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
     *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
     *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
     * };
     */
    class Solution {
    public:
        vector<vector<int>> levelOrder(TreeNode* root) {
            
            vector<vector<int>> ret;
            if(root == nullptr) return ret;
            vector<int> v;
            int front = -1, back = 0, tmp = 0;
            queue<TreeNode*> Q;
            Q.push(root);
            while(!Q.empty())
            {
                TreeNode* u = Q.front(); Q.pop();
                front++;
                v.push_back(u->val);
                if(u->left)
                {
                    tmp++;
                    Q.push(u->left);
                }
                if(u->right)
                {
                    tmp++;
                    Q.push(u->right);
                }
                if(front == back)
                {
                    back = tmp;
                    ret.push_back(v);
                    v.clear();
                }
            } 
            return ret;
        }
    };
  • 相关阅读:
    temp12
    temp111
    test.c
    vipLogin.c
    services.c
    request.c
    managerLogin.c
    将博客搬至CSDN
    SpringMabatis整合项目mybatis-configuration.xml核心配置
    logback-test.xml配置文件模板
  • 原文地址:https://www.cnblogs.com/WTSRUVF/p/15525950.html
Copyright © 2011-2022 走看看