递归虽然简单具有可读性,但同时具有栈溢出、重复计算、函数调用开销的缺点,在工程实现上,有些地方需要用迭代来替代递归。
二叉树的Moris遍历又称二叉树的非递归遍历:前序和后序可以看成是一个Moris框架,中序算作另一种框架。
前序Moris:(中,左,右)
vector<int> preMoris(TreeNode* root){
vector<int> ret;
if(root==nullptr){
return ret;
}
stack<TreeNode*> stk;
stk.push(root);
while(stk.empty()==false){
TreeNode* cur=stk.top();
stk.pop();
ret.emplace_back(cur->val);
if(cur->right){
stk.push(cur->right);
}
if(cur->left){
stk.push(cur->left);
}
}
return ret;
}
后序Moris遍历:修改前序Moris达成(中,右,左)-reverse>(左,右,中)即后序
vector<int> postMoris(TreeNode* root){
vector<int> ret;
if(root==nullptr){
return ret;
}
stack<TreeNode*> stk;
stk.push(root);
while(stk.empty()==false){
TreeNode* cur=stk.top();
stk.pop();
ret.emplace_back(cur->val);
if(cur->left){
stk.push(cur->left);
}
if(cur->right){
stk.push(cur->right);
}
}
reverse(ret.begin(),ret.end());
return ret;
}
Moris中序:(左,中,右)
vector<int> inMoris(TreeNode* root){
vector<int> ret;
if(root==nullptr){
return ret;
}
stack<TreeNode*> stk;
TreeNode* cur=root;
while(stk.empty()==false||cur!=nullptr){
if(cur!=nullptr){
stk.push(cur);
cur=cur->left;
}else{
TreeNode* tmp=stk.top();
stk.pop();
ret.emplace_back(tmp->val);
cur=tmp->right;
}
}
return ret;
}