二叉树三序遍历-迭代法
分析:前后写法思想类似,中序写法不同
#include "_myPrint.cpp"
#include "_TreeNode.cpp"
#include "stack"
using namespace std;
class Solution{
public:
vector<int> inTravel_(TreeNode* root){
vector<int> res;
stack<TreeNode*> st;
if (!root) return res;
TreeNode* cur = root;
// 指针空了说明走到底了 栈空了说明未开始或已经结束
while (!st.empty() || cur){
if (cur){ // 指针一直往左下走
st.push(cur);
cur = cur -> left;
}else{ // 指针在最左下时,取出栈顶元素,回退一次
cur = st.top();
st.pop();
res.push_back(cur -> val);
cur = cur -> right;
}
}
return res;
}
vector<int> postTravel(TreeNode* root){
vector<int> res;
stack<TreeNode*> st;
if (!root) return res;
st.push(root);
while (!st.empty()){
TreeNode* tmp = st.top();
res.push_back(tmp -> val);
st.pop();
// 改变入栈顺序,结果为中右左
if (tmp -> left) st.push(tmp -> left);
if (tmp -> right) st.push(tmp -> right);
}
// 反转结果,为左右中
reverse(res.begin(), res.end());
return res;
}
vector<int> preorder(TreeNode* root){ //迭代法前序
stack<TreeNode*> st;
vector<int> res;
if (!root) return res;
st.push(root);
while (!st.empty()){ // 循环终止的条件
TreeNode* tmp = st.top();
res.push_back(tmp -> val);
st.pop();
// 压入栈先右后左 出栈先左后右
if (tmp -> right) st.push(tmp -> right);
if (tmp -> left) st.push(tmp -> left);
}
return res;
}
};
int main(){
Solution s;
TreeNode* root = new TreeNode(8);
TreeNode* l = new TreeNode(7);
TreeNode* r = new TreeNode(6);
root->left = l;
root->right = r;
vector<int> res = s.inTravel_(root);
printCollection p;
p.printVector(res);
}