|
|
注册一亩三分地论坛,查看更多干货!
您需要 登录 才可以下载或查看附件。没有帐号?注册账号 
x
二叉树的层次遍历,总结 5 种方式:
1. use two queues
使用两个 queue 表示当前层和下一层,一边遍历当前层 (current queue) 的时候,一边把 child nodes 加入到下一层 (next queue) 中;
遍历完当前层之后,把 next queue 置换到 current queue,清空 next queue,然后继上一段遍历逻辑。
- void levelOrder(Node *root) {
- if (!root) return;
- queue<Node*> currentLevel, nextLevel;
- currentLevel.push(root);
- while (!currentLevel.empty()) {
- Node *currNode = currentLevel.front();
- currentLevel.pop();
- if (currNode != nullptr) {
- cout << currNode->data << " ";
- nextLevel.push(currNode->left);
- nextLevel.push(currNode->right);
- }
- if (currentLevel.empty()) {
- cout << endl;
- swap(currentLevel, nextLevel);
- }
- }
- }
复制代码
2. use an extra variable to save the next level count of nodes
原理同上,只不过这次是用两个 int 变量来记录当前层和下一层要遍历的元素数量。
- void leverOrder() {
- queue<Node*> q;
- q.push(this->root);
- int cur = 1, next = 0;
- while(!q.empty()) {
- Node *tmp = q.front();
- q.pop();
- --cur;
- if (tmp != nullptr) {
- cout << tmp->item << " ";
- q.push(tmp->left);
- q.push(tmp->right);
- next += 2;
- }
- if(cur == 0) {
- cout << endl;
- cur = next;
- next = 0;;
- }
- }
- }
复制代码
3. sentinel
使用一个 sentinel 变量来标志一层的结尾。
- vector<vector<int>> levelOrder(Node *root) {
- vector<vector<int>> res;
- vector<int> level;
- queue<Node*> q;
- q.push(root);
- Node *sentinel = new Node(-1);
- q.push(sentinel);
- while(!q.empty()) {
- Node *p = q.front();
- q.pop();
- if (p != sentinel) {
- level.push_back(p->data);
- if (p->left != nullptr) {
- q.push(p->left);
- }
- if (p->right != nullptr) {
- q.push(p->right);
- }
- } else {
- res.push_back(level);
- level.clear();
- if (!q.empty()) q.push(node);
- }
- }
- return res;
- }
复制代码
4. bfs
- void levelOrder(Node *root) {
- if (root == nullptr) return;
- queue<Node*> q;
- q.push(root);
- while (!q.empty()) {
- int n = q.size();
- while (n--) {
- Node *p = q.front();
- q.pop();
- cout << p->data << " ";
- if (p->left) q.push(p->left);
- if (p->right) q.push(p->right);
- }
- cout << endl;
- }
- }
复制代码
5. dfs
- void levelOrder(Node *root) {
- function<void(Node*, int, int)> dfs = [&](Node *root, int level, int curLevel) {
- if (root == nullptr) return;
- dfs(root->left, level + 1, curLevel);
- dfs(root->right, level + 1, curLevel);
- };
- dfs(root, 0, 0);
- }
复制代码
总结:
思路无非是 BFS 或 DFS,更直观的是 BFS,需要注意的是如何标志一层的结尾,典型的使用到 queue 并且理解 queue 的操作方式。
|
上一篇: 【经验分享】零基础准备AWS Developer Certification下一篇: 求大神帮助找bug || 134. Gas Station || Brute Force in Java
|