python - 我们可以在 python 中的单个代码中编写有序、前序和后序吗?不使用递归
问题描述
我想在 O(N) 时间复杂度和 O(N) 空间中使用单个代码(前序、后序、中序)对所有二叉树顺序进行编码,使用单个堆栈且不使用递归。
有人可以帮助我吗?
解决方案
下面的代码很容易记住,因为我们只需要更改(3 行代码) ,就像我们在使用递归时所做的那样为left-root-right排序。
有人问了 Python 实现的问题,但由于数据结构与语言无关,所以我发布了这个答案,以便其他人受益。
它是O(N)空间,使用单个堆栈并且没有递归
对于中序遍历
#include <bits/stdc++.h>
using namespace std;
struct node{
int val;
node *left, *right;
node(int x) {
val = x;
left = right = NULL;
}
};
void traversal_trick(node *root) {
//inorder
stack<pair<node*, int>> S;
S.push({root, 0});
while(!S.empty()){
pair<node*, int> t = S.top();
node* cur = t.first;
int state = t.second;
S.pop();
if(cur == NULL or state == 3) continue;
S.push({cur, state+1});
if (state == 0) S.push({cur->left, 0});
else if (state == 1) cout << cur->val << " " ;
else if (state == 2) S.push({cur->right, 0});
}
}
int main()
{
node *root = new node(7);
node *t = root;
root->left = new node(3); root->right = new node(10);
root->left->left = new node(2); root->left->right = new node(5);
root->left->left->left = new node(1);
root->right->left = new node(8);
root->right->right = new node(12);
traversal_trick(root);
}
对于Preorder Traversal:只需更改这部分代码
if (state == 0) cout << cur->val << " " ;
else if (state == 1) S.push({cur->left, 0});
else if (state == 2) S.push({cur->right, 0});
对于后序遍历:只需更改这部分代码
if (state == 0) S.push({cur->left, 0}) ;
else if (state == 1) S.push({cur->right, 0}) ;
else if (state == 2) cout << cur->val << " ";
有关说明,请参阅此
推荐阅读
- c# - 使用具有复杂过滤器语法的外部 API
- node.js - 如何在 NestJs 中动态注入提供程序
- printing - 使用redmon和ghostscript的打印机端口配置,错误无效窗口句柄
- nginx - Reducing outbound transfer in nginx rtmp server
- javascript - 异步/等待、承诺和 .map()
- javascript - JS fs.createReadStream 在 formData.append 之前调整图像大小
- powershell - PowerShell Import-Module SqlServer - 为什么需要“推送”和“弹出”位置?
- javascript - fetch api 无法加载,不支持 url 方案“文件”
- python - AES CTR 解密:Cryptography 和 Cryptodome 给出不同的结果
- sql - 如何快速还原端到端测试对 SQL Server 数据库中的数据更改?