【前序遍历】
void preOrderTraveralWithStack(TreeNode *root){
//NLR 根左右的顺序访问节点
stack<TreeNode*> s;
TreeNode *treeNode = root;
while(treeNode!=NULL || !s.empty()){
//迭代访问节点的左孩子,并入栈
while(treeNode != NULL){
s.push(treeNode);
cout<<treeNode->val<<endl;
treeNode = treeNode->left;
}
//若没有左孩子,则弹出栈顶节点,访问节点右孩子
if(!s.empty()){
treeNode = s.top();
s.pop();
treeNode = treeNode->right;
}
}
}
【中序遍历的非递归方法】
void inOrderTraveralWithStack(TreeNode* root) {
//RNL 右根左 中序遍历
stack<TreeNode*> s;
TreeNode* treeNode = root;
while(treeNode!=NULL || !s.empty()){
while(treeNode != NULL){
s.push(treeNode);
treeNode = treeNode->left;
}
if(!s.empty()){
treeNode = s.top();
s.pop();
cout<<treeNode->val<<endl;//访问节点
treeNode = treeNode->right;
}
}
}
【逆中序遍历的非递归方法】
class Solution {
public:
int cnt=0;
int inOrderTraveralWithStack(TreeNode* root) {
//RNL 右根左 中序遍历
stack<TreeNode*> s;
TreeNode* treeNode = root;
while(treeNode!=NULL || !s.empty()){
while(treeNode != NULL){
s.push(treeNode);
treeNode = treeNode->right;
}
if(!s.empty()){
treeNode = s.top();
s.pop();
cout<<treeNode->val<<endl;//访问节点
treeNode = treeNode->left;
}
}
return 0;
}
};
【后序遍历】
void postOrderTraveralWithStack(TreeNode* root){
stack<TreeNode*> s;
TreeNode *treeNode = root;
TreeNode *lastVisit = NULL; //标记每次遍历最后一次访问的节点
while(treeNode || !s.empty()){//节点不为空,结点入栈,并且指向下一个左孩子
while(treeNode){
s.push(treeNode);
treeNode = treeNode->left;
}
if(!s.empty()){
treeNode = s.pop();
if(treeNode->right == NULL || treeNode->right == lastVisit) {
cout<<treeNode->val<<endl;
lastVisit = treeNode;
treeNode = NULL;
}else{
s.push(treeNode);
treeNode = treeNode->right;
}
}
}
}
【后序遍历的非递归写法二】
void postOrderTraveralWithStack(TreeNode* root){
stack<TreeNode*> s;
TreeNode *treeNode = root;
TreeNode *lastVisit = NULL;
while(treeNode||!s.empty()){
while(treeNode){
s.push(treeNode);
p=p->left;
}
if(!s.empty()){
treeNode=s.top();
if(treeNode->right&&treeNode!=lastVisit){//若右边子
//树存在,且从未被访问过
treeNode=treeNode->right;//转向右子树
s.push(treeNode);//将右子树根节点压入栈
treeNode=treeNode->left;
}else{
s.pop();
cout<<treeNode->val<<endl;
lastVisit=treeNode;
treeNode=NULL;
}
}
}
}
【层次遍历】
void levelOrderWithQueue(TreeNode *root){
Queue<TreeNode*> q;
q.push(root);
TreeNode* treeNode;
while(!q.empty()){
treeNode=q.front();
q.pop();
cout<<treeNode->val<<endl;
if(treeNode->left)
s.push(treeNode->left);
if(treeNode->right)
s.push(treeNode->right);
}
}