leetcode-102. 二叉树的层序遍历
本文最后更新于:2022年7月30日 晚上
层序遍历都忘记了😂
字节飞书:同时使用dfs和bfs来实现
BFS,层序遍历
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| class Solution { public: vector<vector<int>> levelOrder(TreeNode* root) { queue<TreeNode*> q; vector<vector<int> > res; if (root) q.push(root);
while (!q.empty()) { int qsize = q.size(); vector<int> tmp; for (int i = 0; i < qsize; i++) { auto node = q.front(); q.pop(); tmp.push_back(node->val);
if (node->left) q.push(node->left); if (node->right) q.push(node->right); } res.push_back(tmp); } return res; } };
|
DFS,迭代
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| class Solution { public: vector<vector<int>> res;
void dfs(TreeNode* root, int deepth) { if (!root) return; if (deepth >= res.size()) res.push_back(vector<int>()); res[deepth].push_back(root->val);
dfs(root->left, deepth+1); dfs(root->right, deepth+1); }
vector<vector<int>> levelOrder(TreeNode* root) { dfs(root, 0); return res; } };
|