102. Binary Tree Level Order Traversal

来源:互联网 发布:网络开盘抢房技巧 编辑:程序博客网 时间:2024/06/10 05:26

1、题目描述

二叉树的层次遍历。


2、思路

利用queue进行BFS。


3、代码

    vector<vector<int>> levelOrder(TreeNode* root) {        vector<vector<int>> ans;        if(root==NULL) return ans;        queue<TreeNode*>q;        q.push(root);        while(!q.empty()){            int l = q.size();            vector<int>v;            for(int i=0;i<l;i++){                TreeNode* t = q.front();                q.pop();                v.push_back(t->val);                if(t->left)                    q.push(t->left);                if(t->right)                    q.push(t->right);            }            ans.push_back(v);        }        return ans;    }


原创粉丝点击