C++迭代实现前中后序遍历
#include <iostream> #include <vector> #include <stack> using namespace std; struct Treenode { int val; Treenode* left; Treenode* right; Treenode(int _val):val(_val),left(nullptr),right(nullptr){} }; vector<int> inorder(Treenode *root) { //if(root==nullptr) return nullptr; vector<int> v; stack<Treenode*> st; st.push(root); while(!st.empty()) { Treenode *node=st.top(); if(node) { st.pop(); //中序 if(node->right) st.push(node->right);//右节点入栈 st.push(node);//中间节点入栈 st.push(nullptr);//标志 if(node->left) st.push(node->left); //左节点入栈 //前序 //if(node->right) st.push(node->right);//右节点入栈 //if(node->left) st.push(node->left); //左节点入栈 //st.push(node);//中间节点入栈 //st.push(nullptr);//标志 //后序 //st.push(node);//中间节点入栈 //st.push(nullptr);//标志 //if(node->right) st.push(node->right);//右节点入栈 //if(node->left) st.push(node->left); //左节点入栈 } else{//node为nullptr st.pop();//nullptr出栈 node=st.top(); st.pop();//node保留的节点出栈 v.push_back(node->val); } } return v; } int main(int argc, char *argv[]) { Treenode* t1=new Treenode(1); Treenode* t2=new Treenode(2); Treenode* t3=new Treenode(4); Treenode* t4=new Treenode(5); Treenode* t5=new Treenode(6); t4->left=t3; t4->right=t5; t3->left=t1; t3->right=t2; vector<int> v; v=inorder(t4); for(auto it:v) { cout<<it<<" "; } return 0; }