标签:turn return public empty tree null etc div cto
本题是广度优先遍历(BFS)实现树的层次遍历,使用队列实现。
class Solution { public: vector<vector<int>> levelOrder(TreeNode* root) { vector<vector<int>> res; queue<TreeNode*>q; if (root != NULL) { q.push(root); while (!q.empty()) { vector<int> tmp; vector<TreeNode*> T; while (!q.empty()) { TreeNode* t = q.front(); q.pop(); tmp.push_back(t->val); if (t->left != NULL) { T.push_back(t->left); } if (t->right != NULL) { T.push_back(t->right); } } res.push_back(tmp); for (auto x : T) { q.push(x); } } } return res; } };
标签:turn return public empty tree null etc div cto
原文地址:https://www.cnblogs.com/asenyang/p/9739248.html