二叉树的层序遍历(leetcode 102)

102. 二叉树的层序遍历

二叉树的层序遍历(leetcode 102)

/**
 * 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) {
        queue<TreeNode*>q;
        if(root!=NULL)q.push(root);//进队
        vector<vector<int>>ans;
        while(!q.empty()){
            int len=q.size();
            vector<int>s;//s的长度在变化所以得确定一下
            for(int i=0;i<len;i++){
                TreeNode* node=q.front();
                q.pop();
                s.push_back(node->val);
                if(node->left)q.push(node->left);
                if(node->right)q.push(node->right);
            }
            ans.push_back(s);
        }
        return ans;
    }
};
上一篇:102-二叉树的层序遍历


下一篇:ClickHouse-表引擎