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;
    }
};
原文地址:https://www.cnblogs.com/WTSRUVF/p/15525950.html