力扣精选top面试题--------二叉树的层序遍历

在这里插入图片描述

题目链接

思路:
这道题就是bfs模板题,通过使用一个链表(我自己用到了deque,其实不用的)来记录遍历过的某层的节点即可,剩下的就是很典型的bfs套路。

代码:

/**
 * 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) {
    
    
        deque<TreeNode*> q;
        vector<vector<int> > st;
        if(root==NULL) return st;
        q.push_back(root);
        
        while(!q.empty()){
    
    
            vector<int> p;
            int len = q.size();
            for(int i=1;i<=len;++i){
    
    
                TreeNode* k = q.front();
                q.pop_front();
                p.push_back(k->val);
                if(k->left) q.push_back(k->left);
                if(k->right) q.push_back(k->right);
            }
            st.push_back(p);
        }
        return st;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_43743711/article/details/114027814